我在MYSQL中的where子句的case语句中使用了始终为真的语句,例如1 = 1
,语法如下:
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
(始终为true语句)。
您不会使用只编写多条件语句的情况。在你的情况下,它看起来像
Where (tablefield = 'value'
OR tablefield is null)
如果您想使用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而不是表字段时请求一个条件在这种情况下,查询可能如下所示:
从表名中选择*,其中(如果parameterfield_or_variable不为null,则则tablefield='value'否则1=1结束)
或使用parameterfield作为值时(如果parameterfield_or_variable不为null,则则tablefield=parameter_field_or-variable否则1=1结束)
根据问题@KHeaney的回答是正确的。
然而,tsql/sqlserver中的查询(如mysql中所述)将如下所示:
从表名中选择*其中tablefield=@parameterfield--比较输入参数字段和表字段的情况或@参数为空
因此,当@parameterfield为null时,它将显示所有结果,否则它将仅限于输入值。
感谢
您可以尝试。。。
select * from tablename
where tablefield = isnull(@parameter, tablefield)
我知道T-SQL和MySQL都提供COALESCE
,它返回提供的第一个非NULL值。
SELECT *
FROM tablename
WHERE (COALESCE(`tablefield`, 'value') = 'value')