1

I would like to output the result of the dynamic SQL into a variable called @Count but not sure what the syntax or even the code should like to accomplish this.

The code looks as follows:

declare @tab nvarchar(255) = 'Person.person'

declare @Count int
declare @SQL nvarchar(max) = 'select  count(*) from '+ @tab


exec(@SQl)


select @Count

thank you

5
  • Why do you want to use dynamic sql for this... Commented Jul 7, 2017 at 19:20
  • I'd avoid using dynamic SQL unless you absolutely can't avoid it. You end up with no auto complete, and as a whole it's more error prone. Commented Jul 7, 2017 at 19:41
  • Also, there's the SQL Injection issue. It's a very big problem that you should not ignore. Commented Jul 7, 2017 at 19:50
  • Potentially, yes. Depending on what you're passing through and where it's being sourced from, but it's difficult to guarantee a source is clean in that regard. Commented Jul 7, 2017 at 19:54
  • @user2366842 My answer does in fact guarantee that the source is clean. Commented Jul 7, 2017 at 20:21

3 Answers 3

3

Here's another way to do it that also safely addresses the SQL Injection isuues:

/* Counts the number of rows from any non-system Table, *SAFELY* */

-- The table name passed
DECLARE @PassedTableName as NVarchar(255) = 'Person.Person';

-- Make sure this isn't a SQL Injection attempt
DECLARE @ActualTableName AS NVarchar(255)

SELECT  @ActualTableName = TABLE_SCHEMA + '.' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME   = PARSENAME(@PassedTableName,1)
  AND TABLE_SCHEMA = PARSENAME(@PassedTableName,2)

-- make a temp table to hold the results
CREATE TABLE #tmp( cnt INT );

-- create the dynamic SQL
DECLARE @sql AS NVARCHAR(MAX)
SELECT @sql = 'SELECT COUNT(*) FROM ' + @ActualTableName + ';'

-- execute it and store the output into the temp table
INSERT INTO #tmp( cnt )
EXEC(@SQL);

-- Now, finally, we can get it into a local variable
DECLARE @result AS INT;
SELECT @result = cnt FROM #tmp;
Sign up to request clarification or add additional context in comments.

3 Comments

I'm unable to test this, but are you sure you can insert the results of an exec into another table? I tested it on Sybase (closest I have to SQLServer at the moment) and I cannot insert the dynamic sql result into a table.
@RobbieToyota Yes, I am sure. I do it all the time, plus I tested the code before I posted it.
@RobbieToyota Here's a link to the doc with example. learn.microsoft.com/en-us/sql/t-sql/statements/…
2

You can utilize sp_executesql to execute your count() query, and output it @Count.

Try this:

-- Set the table to count from
declare @tab nvarchar(255) = 'Person.person'

-- Assign the SQL query
declare @SQL nvarchar(255) = N'SELECT count(*) FROM ' + @tab

-- Pepare for sp_executesql
declare @Count int
declare @Params nvarchar(100) = N'@Count int output'

-- Set the count to @Count
exec sp_executesql @SQL, @Params, @Count=@Count output

-- Output @Count
select @Count

One last thing: Person.person looks like you might be trying to reference a person column from a Person table. But the above query is a literal representation of what it looks like you're trying to achieve in your question.

11 Comments

Hmmm. Did you actually try this?
Dynamic SQL context cannot see nor modify variables in an outer context.
Great point; that thought about variable scope hadn't crossed my mind. @Jesse just posted an answer that I was about to mention here. I'll modify this to use sp_executeSql shortly.
HI, I have tried it, but i am getting this error message, Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'SELECT'. (1 row(s) affected)
Thanks Again Rob, that really helps a novice like me so I have accepted your answer as its in the context of my question
|
2

The below question is pretty much identical to what you are asking here.

sp_executeSql with output parameter

DECLARE @retval int   
DECLARE @sSQL nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);

DECLARE @tablename nvarchar(50)  
SELECT @tablename = N'products'  

SELECT @sSQL = N'SELECT @retvalOUT = MAX(ID) FROM ' + @tablename;  
SET @ParmDefinition = N'@retvalOUT int OUTPUT';

EXEC sp_executesql @sSQL, @ParmDefinition, @retvalOUT=@retval OUTPUT;

SELECT @retval;

2 Comments

what is @retvalOUT, it is working without declaring it.. Please explain..
@som_1522 It has been a bit on this question, fun to see my old answer. retvalOUT is declared in the parameter definition for sp_executesql. Check out the "SET @ParmDefinition"

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.