DECLARE @cName VARCHAR(MAX),@cField VARCHAR(MAX),@cFieldList VARCHAR(MAX),@cMasterCommand VARCHAR(MAX)
DECLARE @cSourceDatabase VARCHAR(MAX)
DECLARE @cDestinationDatabase VARCHAR(MAX)

SET @cSourceDatabase='ElvySOURCE'
SET @cDestinationDatabase='ElvyWEBNieuw'
SET @cMasterCommand='USE ['+@cSourceDatabase+']'+CHAR(13)
EXEC (@cMasterCommand)

DECLARE curDatabases CURSOR FORWARD_ONLY READ_ONLY FOR
	SELECT o.name FROM dbo.sysobjects o WHERE OBJECTPROPERTY(o.id, N'IsTable') = 1 AND o.name NOT LIKE N'#%' AND xtype = 'U' AND (o.name LIKE 'nsIFR%' OR o.name LIKE 'nsWEB%' OR o.name LIKE 'ElvyIFR%') and NOT o.name LIKE 'nsIFRResultLog%' ORDER BY NAME
OPEN curDatabases
FETCH NEXT FROM curDatabases INTO @cName
WHILE (@@FETCH_STATUS = 0)
	BEGIN
		SET @cFieldList=''
		DECLARE curFields CURSOR FORWARD_ONLY READ_ONLY FOR
			SELECT SC.NAME FROM dbo.sysobjects SO INNER JOIN dbo.syscolumns SC ON SO.id = SC.id WHERE SO.xtype = 'U' AND SO.name=@cName
		OPEN curFields
		FETCH NEXT FROM curFields INTO @cField
		WHILE (@@FETCH_STATUS = 0)
			BEGIN
				SET @cFieldList=@cFieldList+','+@cField
				FETCH NEXT FROM curFields INTO @cField
			END
		CLOSE curFields
		DEALLOCATE curFields
		
		SET @cMasterCommand='TRUNCATE TABLE ['+@cDestinationDatabase+'].dbo.['+@cName+']'
		PRINT (@cMasterCommand)
		EXEC (@cMasterCommand)
		SET @cMasterCommand='SET IDENTITY_INSERT ['+@cDestinationDatabase+'].dbo.['+@cName+'] ON;'
		SET @cMasterCommand=@cMasterCommand+'INSERT INTO ['+@cDestinationDatabase+'].dbo.['+@cName+']('+SUBSTRING(@cFieldList,2,LEN(@cFieldList)-1)+') SELECT '+SUBSTRING(@cFieldList,2,LEN(@cFieldList)-1)+' FROM ['+@cSourceDatabase+'].dbo.'+@cName
		SET @cMasterCommand=@cMasterCommand+';SET IDENTITY_INSERT ['+@cDestinationDatabase+'].dbo.['+@cName+'] OFF'
		PRINT (@cMasterCommand)
		EXEC (@cMasterCommand)
		FETCH NEXT FROM curDatabases INTO @cName
	END
CLOSE curDatabases
DEALLOCATE curDatabases
