MS SQL Server 2008R2
I'm trying to iterate through attaching multiple databases, extracting their data into a master database and then detaching them. Below is a sample of my script. The attach works fine and iterates through all my .mdf files, attaches (and detaches) them; however, the INSERT INTO operations won't work and give syntax error messages. I can run the entire INSERT INTO operation on its own without any issues, but I can't run it inside the loop. What gives?
USE master
GO
--Begin Loop to parse through all 56 county databases
DECLARE @i INT = 0
WHILE (@i < 56)
BEGIN
SET @i = @i+1
DECLARE @countyNum VARCHAR(MAX) = @i
DECLARE @countyDbName VARCHAR(MAX) = 'COUNTY' + @countyNum
DECLARE @countyDir VARCHAR(MAX) = 'C:\Path\To\Each\Database\File' + @countyDbName + '\output.mdf'
--Attach Current Database
EXEC sp_attach_single_file_db @dbname=@countyDbName,
@physname=@countyDir
--Copy Table Content Into Master Database
INSERT INTO CAMA.dbo.AgForest SELECT * FROM @countyDbName.AgForest
INSERT INTO CAMA.dbo.Appeal SELECT * FROM @countyDbName2.Appeal
INSERT INTO CAMA.dbo.Assessment SELECT * FROM @countyDbName2.Assessment
INSERT INTO CAMA.dbo.AssessmentCA SELECT * FROM @countyDbName2.AssessmentCA
INSERT INTO CAMA.dbo.AssessmentPP SELECT * FROM @countyDbName2.AssessmentPP
INSERT INTO CAMA.dbo.ClassCodes SELECT * FROM @countyDbName2.ClassCodes
--Detach Current Database and Move to Next
EXEC sp_detach_db @dbname=@countyDbName, @skipchecks='true';
END