我有一种情况,我试图过滤那些有信用的人。这是一个Dapper查询示例供参考:
var sql = @"
SELECT *
FROM Person
WHERE (Person.Credits > 0) = @hasCredits";
Connection.Query(sql, new { hasCredits });
我非常确定Postgres允许你这样做,因此当我在SQL Server上使用Incorrect syntax near '='
失败时,我感到很惊讶。
使用下面的示例数据,我希望查询在hasCredits为FALSE时返回ID为1的Person,当hasCredits为TRUE时返回ID为2的Person。
INSERT INTO Person (PersonId, Credits) VALUES (1, 0), (2, 0);
在SQL Server中有没有办法评估表达式的计算结果是true还是false?
我考虑过以下(可怕的)选项,但希望有一个更优雅的解决方案:
"WHERE (Person.Credits " + (hasCredits ? ">" : "=") + " 0)"
"WHERE (@hasCredits = 1 AND Person.Credits > 0) OR (@hasCredits = 0 AND Person.Credits = 0)"
答案 0 :(得分:2)
考虑到当Has credits
单选按钮被选中时,@hasCredits
变量将1
当选择Doesn't have credits
时@hasCredits
变量将0
变量@hasCredits
其他null
变量将为SELECT *
FROM Person
WHERE (Person.Credits > 0 and @hasCredits=1) or --Has credits
(Person.Credits <1 and @hasCredits=0) or --Doesn't have credits
(@hasCredits IS NULL) --Don't care
{{1}}
答案 1 :(得分:1)
你的问题非常简单,答案非常简单!
case when Person.Credit > 0 then 1 else 0 end = @hasCredits