1

How do I save the result of my exeuction into a variable? I want to save the integer given by the count into a variable

    DECLARE @count INT

    SET @sqlString = 'SELECT COUNT (DISTINCT process) FROM @tableName
        + ' WHERE process =''' + @process + '''' + 'AND stage ='
        + '''' + @varStage+ ''''

        PRINT @sqlString
    SET @count = EXEC (@sqlString)

This is my idea, but the last line does not work.

3
  • 1
    does not work? with what error? Commented Jun 25, 2014 at 15:38
  • Incorrect syntax near the keyword 'EXEC'. Commented Jun 25, 2014 at 15:39
  • 2
    possible duplicate of Assign result of dynamic sql to variable Commented Jun 25, 2014 at 15:39

1 Answer 1

1
EXEC doesn't return the count value, you need to select @count within the statement


 Create Table #Temp(Number int)
 DECLARE @count INT

    SET @sqlString = 'Insert Into #Temp SELECT COUNT (DISTINCT process) FROM @tableName
        + ' WHERE process =''' + @process + '''' + 'AND stage ='
        + '''' + @varStage+ ''''

  PRINT @sqlString
  EXEC (@sqlString)

  Select @count = Count(*)
  From #Temp
Sign up to request clarification or add additional context in comments.

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.