sql server 中 where 子句中的 case 语句与 else 始终为真

Case statement in sqlserver in where clause with else as always true

我使用了永远正确的陈述,例如1 = 1 in case 语句 MYSQL 中 where 子句的语法如下:

select * from tablename where 
(case when tablefield is not null then 
 then tablefield = 'value'
else 1 = 1 end)

我想知道如何在 where 子句的 sqlserver/tsql case 语句中使用 else 1 = 1(始终为真语句)。

你不会使用 case 你只会写一个多条件语句。在你的情况下它看起来像

Where (tablefield = 'value'
       OR tablefield is null)

我知道 T-SQL 和 MySQL 都提供了 COALESCE,其中 returns 提供了第一个非 NULL 值。

SELECT *
FROM tablename
WHERE (COALESCE(`tablefield`, 'value') = 'value')

如果你想使用 TSQL CASE 函数,你可以这样做:

select * from tablename where 1 = 
(case when tablefield is not null then 
    (case when tablefield = 'value' then 1 else 0 end)
 else 1 end) 

可以简化为:

select * from tablename where 1 = 
(case when tablefield is null then 1 when tablefield = 'value' then 1 
else 0 end)

您可以省略 "else 0" 部分,因为当找不到匹配项时,返回 NULL(不等于 1)。即:

select * from tablename where 1 = 
(case when tablefield is not null then 
    (case when tablefield = 'value' then 1 end)
 else 1 end) 

select * from tablename where 1 = 
(case when tablefield is null then 1 when tablefield = 'value' then 1 end)

抱歉,我只是混淆了查询,我是想询问参数变量为 null 而不是 tablefield 的条件 在那种情况下,查询可能如下所示:

select * 来自表名 where (当 parameterfield_or_variable 不为 null 时 然后表字段 = 'value' 否则 1 = 1 结束)

或者当使用参数字段作为值时 (当 parameterfield_or_variable 不为 null 时 然后表字段 = parameter_field_or_variable 否则 1 = 1 结束)

@KHeaney 提出的问题的答案是正确的。

但是 tsql/sqlserver 中描述的 mysql 中的查询将是这样的:

select * 来自表名 其中表字段 = @parameterfield -- incase 将输入参数字段与表字段进行比较 或者 @parameter 为 null

所以当@parameterfield 为 null 时,它将显示所有结果,否则它将仅限于输入值。

谢谢

你可以试试...

select * from tablename
where tablefield = isnull(@parameter, tablefield)