I have a dynamic sql statement that may or may not return any results. For simplicity sake:
--other SQL statements defining @a
DECLARE @sql varchar(128)
SELECT @sql = 'SELECT a, b FROM c WHERE a = ' + @a
EXEC(@sql)
I want the results if this statement returns any but if EXEC(@sql) does not return any results how can I go about making it return a single null instead?
I am working with MS SQLServer 2000.
EXPLANATION FOR X-ZERO
This is for use in a webapp ajax response. I am not able to alter the backend java framework which requires a resultset of some kind to be returned by the query to the webservice.
SOLUTION
In case anyone else has this question and because it wasn’t totally clear in the answers, this worked:
--other SQL statements defining @a
DECLARE @sql varchar(128)
SELECT @sql = 'SELECT a, b FROM c WHERE a = ' + @a
EXEC(@sql)
IF @@ROWCOUNT = 0 SELECT null
You can get the result set record count of the statement with the same WHERE clause, and it it is zero, then you can just return one record with null value.
Example:
Hope this helps you!