与此 C# 语句等效的 SQL 是什么?
bool isInPast = (x != null ? x < DateTime.Now() : true)
我需要构造一个WHERE
检查 x < NOW()
的子句仅当 x IS NOT NULL
。 x
是 datetime
有时需要为空,而其他时候则不需要为空,我只想要 WHERE
子句考虑非空值,并将空值视为 true。
现在的条款是:
dbo.assignments.[end] < { fn NOW() }
这适用于非 NULL 情况,但 NULL 值似乎总是使表达式计算为 false。我尝试过:
dbo.assignments.[end] IS NOT NULL AND dbo.assignments.[end] < { fn NOW() }
这似乎没有效果。
最佳答案
要在 WHERE 子句中使用,您必须单独测试
where dbo.assignments.[end] is null or dbo.assignments.[end] < GetDate()
或者您可以将空值转换为日期(始终为真)
where isnull(dbo.assignments.[end],0) < GetDate()
或者您可以对从下面派生的位标志进行否定测试
where case when dbo.assignments.[end] < GetDate() then 0 else 1 end = 1
下面是说明以及如何为 SELECT 子句派生 isInPast。
bool isInPast = (x != null ? x < DateTime.Now() : true)
bool 值只能有两个结果之一:true 或 false。
仔细查看您的标准,错误的唯一条件是何时
x != null && x < now
考虑到这一事实,它就变得很容易翻译,因为在 SQL 中,x < now
只能在 x!=null
时进行评估,因此只需要一个条件
isInPast = case when dbo.assignments.[end] < { fn NOW() } then 0 else 1 end
(1为真,0为假)
不知道什么{ fn NOW() }
表示,但如果希望 SQL Server 提供当前时间,请使用 GETDATE(),或者如果您正在使用 UTC 数据,请使用 GETUTCDATE()
isInPast = case when dbo.assignments.[end] < GetDate() then 0 else 1 end
关于SQL 检查 WHERE 子句中的 NULL(三元运算符?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4953788/