将两个select语句组合到where子句中

时间:2022-02-26 09:35:52

I would like to combine the two select statement below with if else statement into one select statement with the conditional expression in where clause. How could it be achieve?

我想将下面的两个select语句与if else语句组合为一个select语句,并在where子句中使用条件表达式。怎么可能实现呢?

@DefaultMemberID = 2

IF @DefaultMemberID IS NOT NULL THEN 
   SELECT * FROM MemberProfile
   WHERE MemberID = @DefaultMemberID OR MemberID = NULL
ELSE
   SELECT * FROM MemberProfile

How to combine this into one select statement as follow:

如何将此合并为一个select语句,如下所示:

SELECT * FROM MemberProfile
WHERE
  WHEN @DefaultMemberID IS NOT NULL THEN
  MemberID = @DefaultMemberID OR MemberID IS NULL
  ELSE do not take memberID into account when querying

2 个解决方案

#1


1  

I know you are going to have trouble believing this but that is just

我知道你很难相信这是真的

WHERE @DefaultMemberID is null 
   or MemberID = @DefaultMemberID 
   OR MemberID is NULL

#2


2  

This is the way to combine your queries.

这是组合查询的方法。

SELECT * FROM MemberProfile
   WHERE MemberID = @DefaultMemberID OR MemberID IS NULL OR @DefaultMemberID IS NULL
OPTION(RECOMPILE)

Note : You cannot compare NULL with = operator. You need to use IS to check the existence of NULL

注意:不能将NULL与=运算符进行比较。您需要使用的是检查NULL的存在性

#1


1  

I know you are going to have trouble believing this but that is just

我知道你很难相信这是真的

WHERE @DefaultMemberID is null 
   or MemberID = @DefaultMemberID 
   OR MemberID is NULL

#2


2  

This is the way to combine your queries.

这是组合查询的方法。

SELECT * FROM MemberProfile
   WHERE MemberID = @DefaultMemberID OR MemberID IS NULL OR @DefaultMemberID IS NULL
OPTION(RECOMPILE)

Note : You cannot compare NULL with = operator. You need to use IS to check the existence of NULL

注意:不能将NULL与=运算符进行比较。您需要使用的是检查NULL的存在性