Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if SQL stored in a variable will return any rows

If I have a SQL script stored in a variable like this:

DECLARE @SQL VARCHAR(MAX) = 'SELECT * FROM Employees WHERE Age > 80'

How can I tell if @SQL would return any rows if I were to run it?

In effect this:

IF EXISTS(@SQL) print 'yes, there are rows' -- Dummy code -- does not work!

I would like to try this without having to run the script in @SQL, insert that into a table and them count the rows.

like image 547
Craig Avatar asked Oct 10 '11 21:10

Craig


People also ask

How do you check if data exists in a column SQL?

The SQL EXISTS Operator The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.

How do I return the number of rows affected by a stored procedure?

DBCOUNT returns the number of rows affected by the last select statement executed by the stored procedure. For example, if the last two statements executed by the procedure are select and update statements, DBCOUNT returns the number of rows affected by the select, not by the update.

How will you check a stored procedure return records in SQL Server?

Return Value in SQL Server Stored Procedure In default, when we execute a stored procedure in SQL Server, it returns an integer value and this value indicates the execution status of the stored procedure. The 0 value indicates, the procedure is completed successfully and the non-zero values indicate an error.


2 Answers

Of course you need to run the script. To avoid having to insert the result into a table and count the rows you can use sp_executesql and an output parameter.

DECLARE @Statement NVARCHAR(MAX) = 'SELECT * FROM Employees WHERE Age > 80'

DECLARE @DynSQL NVARCHAR(max) = N'SET @Exists = CASE WHEN EXISTS(' + 
                                @Statement + 
                                N') THEN 1 ELSE 0 END'

DECLARE @Exists bit
EXEC sp_executesql @DynSQL,
                   N'@Exists bit OUTPUT',
                   @Exists = @Exists OUTPUT

SELECT @Exists AS [Exists]
like image 117
Martin Smith Avatar answered Nov 07 '22 04:11

Martin Smith


While Martin's answer is also valid but can't we just use the @@RowCount after Executing the script? like

DECLARE @q nvarchar(max);
SET @q = 'declare @b int; select * from sys.tables where @b = 5';

EXEC (@q);

If @@RowCount > 0
    Print 'Rows > 0';
Else
    Print 'Rows = 0';

Note that the query has a variable declaration in it, which obviously cannot be used with Exists()

like image 45
sallushan Avatar answered Nov 07 '22 04:11

sallushan