sql查询中的条件
我想在sql查询中插入如下内容:sql查询中的条件,sql,sql-server,tsql,Sql,Sql Server,Tsql,我想在sql查询中插入如下内容: Select * from Users where id=[if @userId>3 then @userId else "donnt use this condition"] and Name=[switch @userId case 1:"Alex" case 2:"John" default:"donnt use this condition"]; 我怎么做 还有一个类似的问题 当showAll为false时,它工作正常,但当showAll为t
Select * from Users where id=[if @userId>3 then @userId else "donnt use this condition"] and Name=[switch @userId
case 1:"Alex"
case 2:"John"
default:"donnt use this condition"];
我怎么做
还有一个类似的问题
当showAll为false时,它工作正常,但当showAll为true时,它不返回任何内容。为什么以及如何使其正常工作?IsClosed列具有位类型
Select * from orders where IsClosed=CASE WHEN @showAll='false' THEN 'false' ELSE NULL END;
这将表现得非常糟糕:
Select *
from Users
where (@userid > 3 AND id = @userId)
OR (@userId BETWEEN 1 AND 2 AND name = CASE
WHEN @userId = 1 THEN 'Alex'
ELSE 'John'
END)
性能最好的选项是动态SQL:
SQL Server 2005+
有关SQL Server动态SQL支持的详细信息,请阅读“”请尝试以下操作:
select *
from Users
where id = (case when @userId > 3 then @userId
else id end)
and Name = (case cast(@userId as varchar)
when '1' then 'Alex'
when '2' then 'John'
else Name end)
或者我认为这会表现得更好:
select aa.*
from (select *
, case when @userId > 3 then @userId
else id end as UserID
, case cast(@userId as varchar)
when '1' then 'Alex'
when '2' then 'John'
else Name end as UserName
from Users) aa
where aa.id = aa.UserID
and aa.Name = aa.UserName
您可能希望定义仅在选择中需要的每个字段,而不是使用星号(*
)
select *
from Users
where id = (case when @userId > 3 then @userId
else id end)
and Name = (case cast(@userId as varchar)
when '1' then 'Alex'
when '2' then 'John'
else Name end)
select aa.*
from (select *
, case when @userId > 3 then @userId
else id end as UserID
, case cast(@userId as varchar)
when '1' then 'Alex'
when '2' then 'John'
else Name end as UserName
from Users) aa
where aa.id = aa.UserID
and aa.Name = aa.UserName