Tyler
Tyler

Reputation: 3813

SQL Server : check data if available otherwise use IS NULL

I have a stored procedure where I need to pull data based on 5 values, but sometimes one of the values is empty. The column though is not empty but NULL, so I need it to somehow check if it is NULL.

Here is my code:

SELECT UVC 
FROM [Blackbook].[VehicleUvc]  
WHERE Year = @Year 
  AND Make = @Make 
  AND Model = @Model 
  AND Series = @Series 
  AND Style = @Style

So the @Series sometimes is an empty string and so I would need it to check if it is null when it is empty, otherwise it will do what it is currently doing, and look up the data based on the normal value. Is that something I can do in the code there or is there something I have to do when declaring the variable?

Something like:

IF (@Series = '') { Series IS NULL } ELSE { Series = @Series }

Upvotes: 0

Views: 53

Answers (1)

artm
artm

Reputation: 8584

You can use ISNULL on the table column, if it's null take it as '' so if the variable is '' they'll match when the column is null:

SELECT UVC 
FROM [Blackbook].[VehicleUvc] 
WHERE ISNULL(Year, '') = @Year 
    AND ISNULL(Make, '') = @Make 
    AND ISNULL(Model, '') = @Model 
    AND ISNULL(Series, '') = @Series 
    AND ISNULL(Style, '') = @Style

Upvotes: 1

Related Questions