[英]use case in where clause sql server
我试图做的是使查询考虑或不是日期时间值,所以我不必在存储过程中这样做
if @considerDate =1
begin
select * from table
where dateCol = @date
end
else
begin
select * from table
end
我想做一些想法
select * from table
where dateCol = ( case
when @date is not null
then @date
)
在单个查询中
你只需要添加END
关键字
SELECT *
FROM tableName
WHERE dateCol = CASE WHEN @considerDate =1
THEN @date
ELSE dateCol
END
如果我理解正确,这应该有效:
SELECT *
FROM Table
WHERE dateCol =
CASE WHEN @date is not null then @date ELSE dateCol END
if @considerDate =0
begin
-- set the variable to null so the select will return all rows from table
set @date = null
end
SELECT *
FROM table
WHERE dateCol = IsNull(@date, dateCol)
如果您不想在查询中包含date参数,请将值设置为null,并且在查询中,您可以使用空检查来确定它是否将应用过滤器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.