I need to write a stored procedure that accepts a variable (actually, several of them, but will simplify it for this purpose), then builds a SQL statement which filters based on that variable. However, it is optional for the user to pass that variable or not. If the user doe not pass the variable, the filter must ignore that piece, instead of returning Null values.
Basically, what I’ve got is:
@VariableA varchar(50)
@SQL nvarchar(max)
Select @SQL = 'Select ColumnX from TableY where (('+@VariableA+ ' = somevalue) or (@VariableA is null))'
exec sp_executesql @SQL
So, my problem is that when the @SQL string executes as a query, the @VariableA variable is out of scope. How can I write the dynamic SQL query to run, but also check the variable for a null value, if the user does not pass it?
You need to add a couple more parameters here, and you don’t need to concatenate the variable in the @SQL string, the extra variables tell the dynamic SQL what should be referenced:
You’ll need to set @VariableA approiately prior to the dynamic SQL.
More info: http://msdn.microsoft.com/en-us/library/ms188001(v=sql.100).aspx