thanks everyone for your help. i was able to work through it.
apart from the major brain freeze of getting my IDENTITY_INSERT OFF and ONs mixed up (and who hasn't done that before ) it was as i had feared - i needed to specify the column names - SELECT * just couldn't handle it.
so i wrote a small function that built a comma separated list of all the column names for the table name and used that in the SELECT statement (i included it below). and i alos modified the code to use the correct ON and OFF.
i also never realised that you could only have one ON per session so the OFF after the INSERT was added.
thanks to everyone.
working code:
- ALTER FUNCTION dbo.arc_udfGetTableColumns
- (
- @tablename VARCHAR(200)
- )
- RETURNS VARCHAR(5000)
- AS
- BEGIN
- DECLARE @rc VARCHAR(5000)
- DECLARE @colName VARCHAR(200)
- DECLARE @comma VARCHAR(2)
-
- SELECT @rc = ''
- SELECT @comma = ''
-
- DECLARE curColumns CURSOR LOCAL FORWARD_ONLY STATIC FOR
- SELECT [name] FROM syscolumns
- WHERE id = (SELECT id FROM sysobjects WHERE type = 'U' AND [NAME] = @tablename)
- ORDER BY colorder
-
- OPEN curColumns
- FETCH NEXT FROM curColumns INTO @colName
-
- WHILE (@@FETCH_STATUS >= 0)
- BEGIN
- IF @@FETCH_STATUS < 0
- BREAK
-
- SELECT @rc = @rc + @comma + @colName
- SELECT @comma = ', '
-
- FETCH NEXT FROM curColumns INTO @colName
- END
-
- CLOSE curColumns
- DEALLOCATE curColumns
-
- RETURN @rc
- END
so the original INSERT code above becomes :
- SELECT @cols = dbo.arc_udfGetTableColumns(@tablename)
-
SELECT @sql = 'DELETE ' + @tablenameEXEC (@sql) SELECT @sql = 'SET IDENTITY_INSERT ' + @tablename + ' ON'EXEC (@sql) SELECT @sql = 'INSERT INTO ' + @tablename + '(' + @cols + ') ' + 'SELECT ' + @cols + ' FROM ' + @DB + '..' + @tablenameEXEC (@sql) SELECT @sql = 'SET IDENTITY_INSERT ' + @tablename + ' OFF'EXEC (@sql)