Recently, I want to use a stored procedure at work, because the value of the drop-down menu passed from the front-end page is not fixed. The data is like this, 0 is all, 1 is male, and 2 is female. When selecting all, it is necessary to be able to query all User, otherwise only male users or female users can be queried, usually written in the stored procedure
declare @sql nvarchar(500), @str nvarchar(20)
set@str = 'and sex = 1'
set @sql = 'select * from 表 where id >0 '+ @str
exec sp_executesql@sql or exec(@sql)
Later, I read a blog and found that there is another way of writing
The following is a solution to achieve multi-conditional query without splicing SQL strings. The first way of writing is that the code is a bit redundant if (@addDate is not null) and (@name <> '') select * from table where addDate = @ addDate and name = @name else if (@addDate is not null) and (@name ='') select * from table where addDate = @addDate else if(@addDate is null) and (@name <> '') select * from table where and name = @name else if(@addDate is null) and (@name = '') select * from table The second way of writing is select * from table where (addDate = @addDate or @addDate is null) and (name = @name or @name = '') the third way is SELECT * FROM table where addDate = CASE @addDate IS NULL THEN addDate ELSE @addDate END,
name = CASE @name WHEN '' THEN name ELSE @name END
Quoting the blog address: http://uule.iteye.com/blog/1988137