SQL查询 - 根据标志获取所有记录

时间:2012-04-25 19:54:32

标签: sql sql-server-2008

为创建新主题道歉。我无法在previous主题中正确构建问题。

我在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.

我希望能够在不使用SELECT的情况下在单个IF ELSE语句中检索记录。 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')) 

1 个答案:

答案 0 :(得分:2)

您可以使用OR:

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

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