Return All Rows if Field is null or blank
How do I make this return all results if @title is null or if its blank ''?
@title varchar
AS
SELECT *
FROM m开发者_如何学Cydb
Where (Title = @title)
Ive been trying to mess around with different ways but I always get no rows returns. I just need to return all the rows, if nothing is inputed into the parameter.
Add:
...
OR @Title IS NULL
OR @Title = ''
The OR
makes it inclusive, and there's no way that you will have @Title
meet more than one of those three criteria (unless your Title
field has NULL
or blank values).
Use:
IF LEN(@title) > 0 THEN
BEGIN
SELECT * FROM mydb t
WHERE t.title = @title
END
ELSE
BEGIN
SELECT * FROM mydb
END
You can use:
SELECT *
FROM mydb
WHERE (LEN(@title) = 0 OR t.title = @title)
...to only use the @title
variable if it's not zero length or NULL, but the statement is not sargable -- it won't perform as well as breaking out the statement to be only what it needs to be for the situation.
精彩评论