3

I have this requirement to be implemented in a stored procedure. Dynamically query the database to get the count of a table, store it in a t-sql variable and then take some decisions based on that.

This is the stored procedure that i am working on . This is throwing some errors as i don't think there is a simple way of assigning the result of a tsql dynamic query to a variable.

CREATE PROCEDURE test
AS
BEGIN
 DECLARE @sql VARCHAR(255)
 DECLARE @cnt int
 SET @sql = 'SELECT COUNT(1) FROM myTable'
 SET @cnt = EXEC(@sql)
 IF (@cnt > 0)
     PRINT 'A'
 ELSE
     PRINT 'B'
END
GO

Could someone tell me if there is a simpler way of achieving this using T-SQL ?

Thanks.

2 Answers 2

6

alternative:

declare @tablename varchar(512) = 'sometable'
declare @sql nvarchar(512) = 'set @count = (select count(*) from ' + @tablename + ')'
declare @count int

execute sp_executesql @sql, N'@count int output', @count=@count output

select case when @count > 0 then 'A' else 'B' end 
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

 SET @sql = 'SELECT @cnt = COUNT(1) FROM myTable'
 EXEC(@sql)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.