我想在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为true时它什么都不返回。为什么以及如何使其正常工作? IsClosed列有一个位类型。
Select * from orders where IsClosed=CASE WHEN @showAll='false' THEN 'false' ELSE NULL END;
答案 0 :(得分:2)
这将表现得非常糟糕:
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:
DECLARE @SQL NVARCHAR(4000)
SET @SQL = 'SELECT u.*
FROM USERS u
WHERE 1 = 1 '
SET@SQL = @SQL + CASE
WHEN @userId > 3 THEN ' AND u.id = @userId '
ELSE ''
END
SET@SQL = @SQL + CASE @userId
WHEN 1 THEN ' AND u.name = ''Alex'' '
WHEN 2 THEN ' AND u.name = ''John'' '
ELSE ''
END
BEGIN
EXEC sp_executesql @SQL, N'@userId INT', @userId
END
有关SQL Server动态SQL支持的更多信息,请阅读“The Curse and Blessings of Dynamic SQL”
答案 1 :(得分:0)
Select *
from Users
where id = CASE WHEN @userId>3 THEN @userId ELSE NULL END
OR name = CASE WHEN @userId = 1 THEN 'Alex' WHEN @UserId = 2 THEN 'John' ELSE NULL END
答案 2 :(得分:0)
请试试这个:
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
上仅需要的每个字段,而不是使用星号(*
)。