Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Null variables in conditions in T-Sql

Tags:

null

tsql

Is there a way to use a variable in the following manner?

DECLARE @ID int;
SET @ID = NULL;
SELECT *
FROM Market market
WHERE market.ID IS @ID

Or is there another way to do this?

Thanks.

like image 984
triangulito Avatar asked Dec 09 '22 06:12

triangulito


2 Answers

You need to do

SELECT *
FROM Market market
WHERE market.ID = @ID OR (@ID IS NULL AND market.ID IS NULL)

Just for completeness at the moment it is still possible to do

SET ANSI_NULLS OFF

SELECT *
FROM Market market
WHERE market.ID = @ID

but you shouldn't. This option is deprecated. Quite an interesting related blog post

like image 157
Martin Smith Avatar answered Jun 03 '23 07:06

Martin Smith


Is there a particular reason that you are trying to stick null into a variable rather than just doing:

SELECT *
FROM Market market
WHERE market.ID IS NULL
like image 39
Cubicle.Jockey Avatar answered Jun 03 '23 07:06

Cubicle.Jockey