Reputation: 567
Either get only those userIDs with the specified @Lastname or if @LastName = 'All' then get all userIDs even if they have NULL values as their LastName.
SELECT userID INTO #table
FROM users
WHERE LastName = CASE
WHEN @LastName = 'All' THEN LastName
ELSE @LastName END
The above query only returns those userIDs where the LastName is not NULL.
Upvotes: 2
Views: 1917
Reputation: 6844
you can also try it-
SELECT * FROM users
WHERE IF(@lastname<>'all',lastname=@lastname,1=1);
In case @lastname contains multiple last name then you can use below query-
SELECT * FROM users
WHERE IF(@lastname<>'all',FIND_IN_SET(lastname,@lastname),1=1);
Upvotes: 0
Reputation: 21757
Change your condition to this instead:
where (@LastName = 'All' and 1=1) or (LastName = @LastName)
The idea is that when @LastName
= 'All' then your query should not have any filters. The 1=1 condition will be always true, and together with the other check should return all results. The other path the query can take is filtering by a specific Last Name, which should definitely exclude null values.
Update: THE 1=1 condition is redundant. You can rewrite the condition as:
where (@LastName = 'All') or (LastName = @LastName)
Upvotes: 3
Reputation: 17061
SELECT userID FROM users
WHERE
CASE WHEN @LastName = 'All' THEN LastName = LastName
ELSE LastName = @LastNam END
;
Upvotes: 0