Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
sql查询-基于标志获取所有记录_Sql_Sql Server 2008 - Fatal编程技术网

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

sql查询-基于标志获取所有记录,sql,sql-server-2008,Sql,Sql Server 2008,为创建新线程而道歉。我没能把问题正确地写在文章里 我在SQLServer2008中有一个表,如下所示- 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 recor

为创建新线程而道歉。我没能把问题正确地写在文章里

我在SQLServer2008中有一个表,如下所示-

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')) 

您可以使用或:

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

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

如果
,为什么不使用
呢?@Oded:我已经尝试过这个-
SELECT*从Status=@Status或@Status为NULL的Person中选择,但它返回的数据不正确。另外,这个
从Person中选择*,其中(@Status不为null,Status=@Status)或(@Status为null,Status in('A','I','P'))
具有相同的结果。@MikaelEriksson:SELECT
语句中有很多连接和内容,我不想在ELSE
条件中重复相同的内容。这是您应该在问题中包括的内容,以及它们不适用于您的原因。@Oded:我下次会记住这一点。对此很抱歉。@JohnDewey:但如果状态为-1,它将返回第3行,而OP似乎不需要它。@MarkByers:我可能遗漏了什么,但它似乎不起作用。我正在使用这个-
SELECT*FROM-Person,其中Status='-1'或(@Status='-1'且Status不为NULL)
。我期待着所有的记录,但我什么也没有得到。@MarkByers:噢,对不起。我对参数和列名感到困惑。工作起来很有魅力。再次感谢@MarkByers:所以我将其合并到原始查询中,查询已经运行了整整五分钟。我手动停止了它。使用此查询时是否存在任何性能问题?表中有1320万条记录。@Enigma:是的,存在性能问题。这就是为什么我在另一个线程上发布了一个使用UNIONALL的替代方案。如果您需要性能方面的帮助,请发布完整的查询、完整的表定义、完整的执行计划,并说明您在所有表上有哪些索引。