SQL 查询 - 基于标志获取所有记录



为创建新线程而道歉。我无法在上一个线程中正确构建问题。

我在 SQL Server 2008 中有一个表,如下所示 -

Id      Status
--------------
1        A
2        I
3        NULL

我有一个以@Status为参数的存储过程。

If the @Status is "-1", I need to retrieve records 1, 2. 
If the @Status is "A", I need to retrieve only record 1.
If the @Status is "I", I need to retrieve only record 2.

我希望能够在不使用IF ELSE的情况下检索单个SELECT语句中的记录。SELECT 语句中有很多连接和东西,我不想在 ELSE 条件下重复同样的事情。

我尝试了以下方法,但得到不正确的数据 -

SELECT * FROM Person WHERE Status = @Status OR @Status IS NOT NULL
select * from Person
where (@Status is not null and Status = @Status) or
      (@Status is null and Status in ('A', 'P')) 
您可以使用

OR来做到这一点:

SELECT *
FROM Person
WHERE Status = @Status
OR (@Status = '-1' AND Status IS NOT NULL)

当然,您不应该在生产代码中使用SELECT *

最新更新