|
|
Question : Must declare the table variable "@table_name".
|
|
I get the following error: Msg 1087, Level 15, State 2, Line 16 Must declare the table variable "@table_name".
In the following code: ============================================= DECLARE c CURSOR FOR SELECT table_name FROM vwAgency_tables WHERE aid = @iAid
OPEN c FETCH next FROM c INTO @table_name WHILE @@fetch_status = 0 BEGIN SELECT @iHitCount = COUNT(*) FROM @table_name WHERE TIN LIKE '%'+@sTIN+'%' -- <--------------- FETCH next FROM c INTO @table_name END CLOSE c DEALLOCATE c =============================================
Is there any way to do this without using EXEC on a varchar?
The end result is that id like to keep a running total count of matches from several tables (those tables are only known at runtime)
|
Answer : Must declare the table variable "@table_name".
|
|
The code: SELECT table_name FROM ... led me to believe you were looking for tables.
Oops .. I didn't realize the system proc used a cursor. Silly me.
Here's a completely non-cursor alternative though it also uses dynamic sql:
--=========================================================== declare @loop int, @sql nvarchar(4000), @Hitcount int Create #c table (uid int identity primary key not null, sql nvarchar(4000) ) insert into #c select 'SELECT @HitCount = @HitCount + COUNT(*) FROM [' + table_name + '] WHERE TIN LIKE ''%' + @sTIN + '%''' FROM vwAgency_tables WHERE aid = @iAid
set @loop = scope_identity() set @Hitcount = 0
while @loop > 0 BEGIN select @sql = sql from #c where uid = @loop exec sp_executeSql @sql, N'@Hitcount int OUTPUT', @Hitcount = @Hitcount OUTPUT set @loop = @loop - 1 end -- loop
select @hitcount as Hitcount --===========================================================
|
|
|
|
|