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.
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.
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.
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.
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]
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With