Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.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_Sql Server 2008 - Fatal编程技术网

Sql 基于参数从表中获取行

Sql 基于参数从表中获取行,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我想根据参数值从中获取行。它可以是值“ABC”或NULL。下面是源表和预期结果,我正在努力实现 源表 尝试使用query,但得到两行,分别为value1和value2 Declare @Param1 varchar(20) = 'ABC' Select * from SourceTable where column2 = @Param1 Or column2 is NULL 如果值为“ABC”,则结果为- 如果值为空,则结果为- 也许这对你有用 select * from Source

我想根据参数值从中获取行。它可以是值“ABC”或NULL。下面是源表和预期结果,我正在努力实现

源表

尝试使用query,但得到两行,分别为value1和value2

Declare @Param1 varchar(20) = 'ABC'

Select * 
from SourceTable 
where column2 = @Param1 Or column2 is NULL
如果值为“ABC”,则结果为-

如果值为空,则结果为-


也许这对你有用

select * 
from SourceTable 
where column2 = @Param1 or (@Param1 is null and column2 is null)

也许这对你有用

select * 
from SourceTable 
where column2 = @Param1 or (@Param1 is null and column2 is null)

您可以尝试这样的方法:您可能遇到的唯一问题是您的第2列是否有空格

SELECT * 
FROM SourceTable 
WHERE ISNULL(column2, '') = ISNULL(@Param1, '')

您可以尝试这样的方法:您可能遇到的唯一问题是您的第2列是否有空格

SELECT * 
FROM SourceTable 
WHERE ISNULL(column2, '') = ISNULL(@Param1, '')
也许你想让所有人联合起来,并检查他们的存在:

Select *
from SourceTable
where column2 = @Param1
union all
Select *
from SourceTable
where column2 is null and not exists (select 1 from sourcetable st2 where st2.column2 = @Param1);
如果只需要一行,则另一种方法使用order by-:

select top 1 st.*
from sourcetable st
where column2 = @param1 or column2 is null
order by (case when column2 is not null then 1 else 2 end);
也许你想让所有人联合起来,并检查他们的存在:

Select *
from SourceTable
where column2 = @Param1
union all
Select *
from SourceTable
where column2 is null and not exists (select 1 from sourcetable st2 where st2.column2 = @Param1);
如果只需要一行,则另一种方法使用order by-:

select top 1 st.*
from sourcetable st
where column2 = @param1 or column2 is null
order by (case when column2 is not null then 1 else 2 end);

也许这里没什么好担心的,但你可能会读到关于ISNULL和sargable的文章……我想说的是,SARGability总是值得担心的。这个查询的性能可能还可以,但其他人会过来复制它,而不理解为什么另一个查询速度如此之慢。一旦知道有问题,就很容易解决也许这里没什么好担心的,但你可能会读到关于ISNULL和sargable的文章……我想说的是,SARGability总是值得担心的。这个查询的性能可能还可以,但其他人会过来复制它,而不理解为什么另一个查询速度如此之慢。一旦知道有问题,就很容易解决