Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

make a count a local variable 1

Status
Not open for further replies.

revilord

Programmer
Oct 2, 2003
64
I trying to get a count from a number of tables and use that count as a variable in MS SQL. I have to get the table names from sysobjects so I am using an EXEC. here's what I want but this won't work. I have let out all the loops and other stuff.

DECLARE @query varchar(100)
DECLARE @counter varchar(5)
DECLARE @table_name varchar(20)
SET @table_name = 'sysusers' --

select @query = 'select count(*) from ' + @table_name
EXEC (@query) = @counter -- this fails
If (CAST (@counter) AS int) = 0
BEGIN
Print '0 reocrds in ' + @table name
END




 
so basically this way, example is using pubs modify for your need

Code:
USE pubs
GO

--sp_executesql
DECLARE @chvTableName VARCHAR(100),
@intTableCount INT,
@chvSQL NVARCHAR(100)

SELECT @chvTableName = 'Authors'
SELECT @chvSQL = N'SELECT @intTableCount = COUNT(*) FROM ' + @chvTableName

EXEC sp_executesql @chvSQL, N'@intTableCount INT OUTPUT', @intTableCount OUTPUT

SELECT @intTableCount
GO

Denis The SQL Menace
SQL blog:
Personal Blog:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top