2

I have a stored procedure where I am declaring an int variable that needs to be populated using a dynamic sql

CREATE PROCEDURE USP_aTABLE_ADD
/*

    stored procedure variables

*/
AS

     DECLARE @count int
     SET @count = 1
     DECLARE @qry nvarchar(max)

/*
     SET UP @qry which will look like this
     SELECT @count = count(*) FROM aTABLE WHERE (col1 = 'val1' AND col2 = 'val2'...)
*/


/*
     How to get the value of @count so that I can continue with add process
*/

IF @count = 0
BEGIN
   /*add logic*/
END
1
  • 1
    Looks like you're already selecting the value of count(*) into @count, so what's the problem? Commented Feb 27, 2014 at 12:11

2 Answers 2

5

Use sp_executeSQL and an output parameter:

DECLARE @count INT = 1
DECLARE @qry   NVARCHAR(MAX)

SET @qry = N'set @count = (....)'

EXEC sp_executesql @qry, N'@count INT OUTPUT', @count OUTPUT
    
SELECT @count
Sign up to request clarification or add additional context in comments.

Comments

2

You could try and work with a temporary table like this

DECLARE @tmp TABLE(cnt INT)
DECLARE @qry nvarchar(max)

-- Insert the count returned by dynamic SQL into temp table
SET @qry = 'SELECT COUNT(*) FROM Table WHERE condition'
INSERT INTO @tmp EXEC(@qry)

DECLARE @count INT
SET @count = (SELECT TOP 1 cnd FROM @tmp)

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.