I have a SQL query which is written in string and then executed using command Exec(string) like the following :
Declare @TestId bigint = null
Declare @Query nvarchar(max)
set @Query = 'SELECT * from Registrations where RegistrationId = 15 AND (' + CAST(@TestId AS NVARCHAR) + ' IS NULL OR TestId = ' + CAST(@TestId AS NVARCHAR) + ') '
EXEC(@Query)
The problem now that the IS NULL is not parsed correctly inside the string but when i remove the IS NULL from the string it works correctly and when the @TestId takes a value other than null it works correctly where the problem now is in the casting of the IS NULL inside the @Query string.
Note : @TestId is a procedure parameter
I need to know how to make the SQL feel with the IS NULL and parse it correctly
Thanks in advance
If you really do need to use dynamic sql for this, use sp_executesql like this: