Solved

How to assign count(*) to a variable using  a dynamically generated statement excecuted by sp_executesql

Posted on 2004-09-22
8
1,138 Views
Last Modified: 2008-01-09
I am trying to perform a select count(*) against a set of tables within a database.  The tablenames and database names are dynamic.  I am trying to assign the count to a variable for inserting into a second table that holds auditing information.

I have tried 2 different approaches thus far and receive different error messages syntax errors:

Approach 1:
declare @RowCount bigint
declare @SourceTable varchar(100)
declare @SourceDatabase varchar(100)
declare @SQLStatement varchar(4000)

set @SourceTable = 'DLctblSource'
set @SourceDatabase = 'discode_Db'
set @RowCount = 0

set @SQLStatement = 'select count(*) from '+ @SourceDatabase +'.dbo.'+ @SourceTable + ''
print @SQLStatement
 execute master.dbo.sp_executesql @SQLStatement
Error Message:  Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'

Approach 2:
declare @RowCount bigint
declare @SourceTable varchar(100)
declare @SourceDatabase varchar(100)
declare @SQLStatement varchar(4000)
set @SourceTable = 'DLctblSource'
set @SourceDatabase = 'discode_Db'
set @RowCount = 0
select @RowCount = count(*) from '+ @SourceDatabase +'.dbo.'+ @SourceTable + '
print @SQLStatement
Error Message: Line 11: Incorrect syntax near '+ @SourceDatabase +'.

I am then trying to insert either the @RowCount value into the audit table or am inserting the results of the select count(*) by

using set @SQLStatement = 'insert into Audit_tbl(tblname,rec_cnt) select  @tblname,count(*) from '+ @SourceDatabase +'.dbo.'+ @SourceTable +)

I am encountering syntax errors with both approaches- getting late in PM on East Coast
0
Comment
Question by:mikevs
8 Comments
 
LVL 69

Expert Comment

by:ScottPletcher
Comment Utility
Method 1 should be used, with some adjustments :-) :


declare @SQLStatement Nvarchar(4000)

set @SQLStatement = N'select @RowCount = count(*) from '+ @SourceDatabase +N'.dbo.'+ @SourceTable + N''
print @SQLStatement
execute master.dbo.sp_executesql @SQLStatement, '@RowCount BIGINT OUTPUT', @RowCount OUTPUT
0
 
LVL 69

Accepted Solution

by:
ScottPletcher earned 500 total points
Comment Utility
CORRECTIONS:

execute sp_executesql @SQLStatement, N'@RowCount BIGINT OUTPUT', @RowCount OUTPUT
0
 

Author Comment

by:mikevs
Comment Utility
declare @SQLStatement Nvarchar(4000)
declare @SourceTable varchar(30)
declare @SourceDatabase varchar(30)
declare @RowCount bigint
set @SourceTable = 'DLctblSource'
set @SourceDatabase = 'DiscoveryStage_Db'
set @RowCount = 0
set @SQLStatement = N'select @RowCount = count(*) from '+ @SourceDatabase +N'.dbo.'+ @SourceTable + N''
print @SQLStatement
execute master.dbo.sp_executesql @SQLStatement, '@RowCount BIGINT OUTPUT', @RowCount OUTPUT

Result:
/*-----------------------------
declare @SQLStatement Nvarchar(4000)
declare @SourceTable varchar(30)
declare @SourceDatabase varchar(30)
-----------------------------*/
select @RowCount = count(*) from DiscoveryStage_Db.dbo.DLctblSource
Server: Msg 214, Level 16, State 3, Procedure sp_executesql, Line 10
Procedure expects parameter '@parameters' of type 'ntext/nchar/nvarchar'.
0
 
LVL 9

Expert Comment

by:paelo
Comment Utility
Is DLctblSource a table or a procedure?

-Paul.
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 6

Expert Comment

by:jchopde
Comment Utility
As ScottPletcher wrote, you need to change this line

execute master.dbo.sp_executesql @SQLStatement, '@RowCount BIGINT OUTPUT', @RowCount OUTPUT

to

execute master.dbo.sp_executesql @SQLStatement, N'@RowCount BIGINT OUTPUT', @RowCount OUTPUT
0
 
LVL 4

Expert Comment

by:davehilditch
Comment Utility
Change this line:

set @SQLStatement = 'select count(*) from '+ @SourceDatabase +'.dbo.'+ @SourceTable + ''

to

set @SQLStatement = 'select count(*) from '+ @SourceDatabase + '.dbo.' + @SourceTable -- <-- why were you adding empty quotes here?

then instead of

execute master.dbo.sp_executesql @SQLStatement

just use:

exec(@SQLStatement)

Technically, exec not quite as fast as sp_executesql, but we are talking milliseconds, and it will work with code above.

Dave Hilditch.
0
 

Author Comment

by:mikevs
Comment Utility
DLctblSource is a table name.  I have a variation of the procedure that goes against SYSINDEXES, but i am not guaranteed that the statistics are always up to date with the execution of this procedure.
0
 
LVL 69

Expert Comment

by:ScottPletcher
Comment Utility
Unfortunately EXEC() will not directly return a query value to the calling code; you have to sp_executeSQL.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now