Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.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
Where子句基于SQL Server中的null和非null列_Sql_Sql Server - Fatal编程技术网

Where子句基于SQL Server中的null和非null列

Where子句基于SQL Server中的null和非null列,sql,sql-server,Sql,Sql Server,桌子 客户机将始终传递有效的col1和col2值以选择表中可能不存在col2的单行。因此,如果col2可用,则它应该返回带有提供的col2的行,否则返回包含col2=null和col1的行 ID | col1 | col2 ------------------------- 1 | val1 | val2 2 | val1 | null 3 | val1 | val3 4 | val5 | null 如何使用单个SQL查询实现这一点?这将起作用。如果没有TOP1,查询可能会选择

桌子

客户机将始终传递有效的col1和col2值以选择表中可能不存在col2的单行。因此,如果col2可用,则它应该返回带有提供的col2的行,否则返回包含col2=null和col1的行

ID | col1 | col2
-------------------------
1  | val1 | val2    
2  | val1 | null
3  | val1 | val3
4  | val5 | null

如何使用单个SQL查询实现这一点?

这将起作用。如果没有TOP1,查询可能会选择2行,因此我命令它首先返回col2不为null的行

return  ID = 2  if col1 = val1 and col2 = val10 
return ID = 3 if col1 = val1 and col2 = val3 

我不确定top 1的解决方案是否更快,有时订购速度非常慢。

您尝试过这个案例吗..什么时候?
select top 1 * from table1 
where col1 = @param1 and (col2 is null or col2 = @param2)
order by case when col2 is null then 1 else 0 end
select * from table1 where col1 = @col1 and col2 = @col2
union
select * from table1 as t where col1 = @col1 and col2 is null
and not exist (select * from table1 as c where c.col1 = t.col1 and c.col2 = @col2)