我想根据条件过滤表格。像 -
CREATE TABLE [dbo].[tblUserInfo](
[Id] [int] NOT NULL,
[TypeName] [int] NOT NULL,
[Value] [decimal](18, 2) NULL,
[Name] [nvarchar](250) NULL,
)
DECLARE @SearchText VARCHAR(250)='aa'
SELECT *FROM tblUserInfo
@SearchText有文本然后按TypeName列过滤, @SearchText为null,然后按名称列过滤。
仅举例。
我怎么能实现这一目标?提前谢谢。
答案 0 :(得分:3)
您的where子句应如下所示:
where (@SearchText is null and Name = '.....') --filter by Name
or (@SearchText is not null and TypeName = '.....') --filter by TypeName
答案 1 :(得分:0)
DECLARE @SearchText VARCHAR(250)='aa'
SELECT *FROM tblUserInfo
WHERE CASE WHEN @SearchText IS NULL THEN Name ELSE 'a' END = CASE WHEN @SearchText IS NULL THEN 'hehe' ELSE 'a' END
AND
(
CASE WHEN @SearchText IS NOT NULL THEN TypeName ELSE 1 END = CASE WHEN @SearchText IS NOT NULL THEN 2 ELSE 1 END
OR
CASE WHEN @SearchText IS NOT NULL THEN TypeName ELSE 1 END = CASE WHEN @SearchText IS NOT NULL THEN 3 ELSE 1 END
)
我试过这样,有没有更好的解决方案?