I have a SQL Server table with a column called Category
. In my user interface, I have a dropdown list of the category. User can select a category and click on a Search
button to filter the results by the category. In the dropdown, the first option is blank. Means if the user wants to see all records from all categories, he can select blank.
我有一个SQL Server表,其中包含一个名为Category的列。在我的用户界面中,我有一个类别的下拉列表。用户可以选择一个类别,然后单击“搜索”按钮以按类别过滤结果。在下拉列表中,第一个选项为空白。意味着如果用户想要查看所有类别的所有记录,他可以选择空白。
In my SQL Select I have 2 statements for this
在我的SQL Select中我有2个语句
IF @Catg IS NULL
Begin
Select *
From Table
End
Else
Begin
Select *
From Table
Where Catg = @Catg
End
The Catg
column in the table will have either a NULL or a category. Is this possible to do in a single SQL statement?
表中的Catg列将具有NULL或类别。这可以在单个SQL语句中执行吗?
3 个解决方案
#1
3
You can use an OR
statement to join the clauses together:
您可以使用OR语句将子句连接在一起:
Select *
From Table
Where Catg = @Catg OR @Catg IS NULL
#2
0
How about
怎么样
SELECT *
FROM yourtable
WHERE (Catg = @Catg) OR (Catg IS NULL)
#3
0
might be ISNULL
solve your problem this will check if values is NULL
then ''
else your VALUE
可能是ISNULL解决你的问题,这将检查值是否为NULL然后''否则你的VALUE
select * from tblName
where ISNULL(Catg , '')= ISNULL(@Catg, ISNULL(Catg , ''))
#1
3
You can use an OR
statement to join the clauses together:
您可以使用OR语句将子句连接在一起:
Select *
From Table
Where Catg = @Catg OR @Catg IS NULL
#2
0
How about
怎么样
SELECT *
FROM yourtable
WHERE (Catg = @Catg) OR (Catg IS NULL)
#3
0
might be ISNULL
solve your problem this will check if values is NULL
then ''
else your VALUE
可能是ISNULL解决你的问题,这将检查值是否为NULL然后''否则你的VALUE
select * from tblName
where ISNULL(Catg , '')= ISNULL(@Catg, ISNULL(Catg , ''))