Click here to Skip to main content
16,004,828 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,
I want to manage dynamically null values in SQL Server procedure. I have prepared following query, where assumed @storecode is the input parameter of stored procedure

SQL
declare @sql nvarchar(2000)
declare @storecode int =null

SET @sql = 'SELECT * FROM mch WHERE storecode = '+convert(varchar,@storecode)+' OR '+convert(varchar,@storecode)+' IS NULL'

print @sql 
EXECUTE sp_executesql @sql


When I pass valid integer value in @storecode it gives desire output, but when I tried to pass @storecode=NULL then it is not giving any output. I want to pass @storecode=NULL

What I have tried:

How to handle null values in dynamic query in SQL Server?
Posted
Updated 13-May-16 0:07am

SQL
declare @sql nvarchar(2000)
declare @storecode int =null
set @storecode = null
SET @sql = N'SELECT * FROM mch WHERE ' + CASE WHEN cast ( @storecode as varchar) IS NULL THEN 'storecode IS NULL' ELSE 'storecode = ' +   cast( @storecode as varchar) END
 print @sql 
 exec( @sql)


updated solution, as per Chill's comment
 
Share this answer
 
v2
Comments
CHill60 12-May-16 4:03am    
If the OP attempts to run the sql an error occurs "Must declare the scalar variable "@storecode"."
Karthik_Mahalingam 12-May-16 4:10am    
HI Chill,
I am sorry, i was focused on building the query rather than testing it with exec,
I will come back with a solution..
It would appear that you want to filter the results if @storecode is provided but if it is null then you want the entire table returned.

Probably the easiest/clearest way is this
declare @sql nvarchar(2000)
declare @storecode int = null
 
SET @sql = 'SELECT * FROM mch '  
IF @storecode IS NOT NULL 
	SET @sql = @sql + 'WHERE storecode = ' + CAST(@storecode as varchar)


The reason that you are not getting anything with your current query is because the use of NULL within the construction of the string renders the entire string NULL.
 
Share this answer
 
Comments
Karthik_Mahalingam 12-May-16 4:23am    
Hi Chill
i have updated my solution.
used the CAST( trick from yours :)
Its simple. USE ISNULL function to handle null value
SQL
declare @sql nvarchar(2000)
declare @storecode int =null
 
SET @sql = 'SELECT * FROM mch WHERE storecode = '+convert(varchar,ISNULL(@storecode,1))+''
 
print @sql 
EXECUTE sp_executesql @sql


Thanks.
 
Share this answer
 
v2
Comments
CHill60 13-May-16 6:24am    
I disagree. This will return the same as if @storecode = 1 - which does not appear to be what the OP wants. If there is a default value then, yes this would work. But that behaviour does not fit any real business scenario so is unlikely

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900