2

I am attempting to build a query on the fly that will set a variable. How would I do this?

Here is what I have so far

DECLARE @SQL as NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)

set @SQL = 'set @maxRowCount = (select count(*) from Test)'
SET @ParmDefinition = N'@maxRowCount int';

EXECUTE sp_executesql @SQL, @ParmDefinition

When I run this I get the following error

Msg 8178, Level 16, State 1, Line 1
The parameterized query '(@maxRowCount int)set @maxRowCount = (select count(*) from docto' expects the parameter '@maxRowCount', which was not supplied.

I am trying to get @maxRowCount to be set to the total row count of the Test table

2
  • do you actually need to use dynamic sql here or is this just a simplified example? Commented Jun 24, 2015 at 15:20
  • This is a very simplified example. Commented Jun 24, 2015 at 15:30

1 Answer 1

2

This works, you need the 'OUTPUT' in the parameter definition and a place where the result goes to as well

DECLARE @SQL as NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)
DECLARE @iRowCount INT
SET @SQL = 'set @maxRowCount = (select count(*) from Test)'
SET @ParmDefinition = N'@maxRowCount INT OUTPUT';

EXECUTE sp_executesql @SQL, @ParmDefinition, @maxRowCount = @iRowCount  OUTPUT

PRINT 'rowcount is:' + CONVERT(VARCHAR,@iRowCount)
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.