Reputation: 709
I am trying to insert values into a temp table from within a cursor loop. It is hard to explain so I will just show what I have so far.
declare @sqlStatement varchar(max)
declare @tmpTable table (
Table_Name varchar(max)
,Count int
)
declare cur CURSOR FAST_FORWARD FOR
Select
'Select ''' + TABLE_NAME + ''' [Table_Name],COUNT(*) [Count] From [' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'
from information_schema.tables
Where TABLE_TYPE = 'BASE TABLE'
OPEN cur
FETCH NEXT FROM cur
INTO @sqlStatement
WHILE @@FETCH_STATUS = 0
BEGIN
declare @tmp varchar(max) = 'INSERT INTO @tmpTable ' + @sqlStatement
exec @tmp
Select * From @tmpTable
fetch next from cur
into @sqlStatement
END
CLOSE cur
DEALLOCATE cur
And I am getting the error
The name 'INSERT INTO @tmpTable Select 'table' [Table_Name],COUNT(*) [Count] From [dbo].[table]' is not a valid identifier.
But I don't see anything wrong with that statement. I think it may have to do with the escape characters in within the string?
Upvotes: 0
Views: 2331
Reputation: 11
There are couple of issues, your while loop is missing 'FETCH NEXT FROM cur INTO @sqlStatement' which will lead it to indefinite loop. But this is not really the problem here. use exec ( ) with brackets it should solve the problem.
declare @tmpTable table (
Table_Name varchar(max),
CountX int
)
insert into @tmpTable
SELECT sc.name +'.'+ ta.name TableName
,SUM(pa.rows) CountX
FROM sys.tables ta
INNER JOIN sys.partitions pa
ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY sc.name,ta.name
ORDER BY SUM(pa.rows) DESC
select * from @tmpTable
Upvotes: 1
Reputation: 7616
Try using an actual temp table instead of a variable. Dynamic SQL needs to reference database objects.
create table #tmpTable (
Table_Name varchar(max)
,Count int
)
Upvotes: 1
Reputation: 175926
The format for the exec
call must include parentheses:
exec(@tmp)
You will also need to change to a #temp
table as a table variable will not be within the scope of the exec
'd batch.
Upvotes: 2