Dynamic sql generation script for insert into select from table

Hello everyone,

I'm attempting to create a script that dynamically generates one or more "insert into" statements with all columns properly defined (SQL Server 2012).

Here's what I have so far:

use source_db;
GO

create table table1
(
	column1 int
	,column2 varchar(10)
	,column3 datetime
);

create table table2
(
	column1 int
	,column2 varchar(10)
	,column3 datetime
);


use target_db;
GO

Declare @Tables as Table
(
	TableName	Varchar(50)
);

insert into @Tables 
(TableName)
select TableName 
from
(        
		SELECT 'table1' as TableName       
		UNION ALL SELECT 'table2'							
)a

declare @SQL nvarchar(max);

select @SQL = COALESCE(@SQL + '
', '')
+ CASE WHEN ROW_NUMBER() OVER(PARTITION BY a.TableName ORDER BY c.column_id) = 1 and ROW_NUMBER() OVER(ORDER BY a.TableName, c.column_id) <> 1 THEN 
'		)

' 
ELSE ''
END
+ CASE WHEN ROW_NUMBER() OVER(PARTITION BY a.TableName ORDER BY c.column_id) = 1
	THEN
		'
		INSERT INTO [target_db].[dbo].['+a.TableName+']
		( 
			['+c.name+']'
	ELSE
	'			,['+c.name+'] '
END
FROM @Tables a
INNER JOIN source_db.sys.Objects o
on o.Name = a.TableName
INNER JOIN source_db..sys.Columns c
on c.object_id = o.object_id
INNER JOIN source_db..sys.Types t
on c.user_type_id = t.user_type_id
Where o.type = 'U'

print @SQL

Open in new window


That script puts out a result that looks like this:

INSERT INTO [target_db].[dbo].[table1]
(
     column1
     ,column2
     ,column3

)

INSERT INTO [target_db].[dbo].[table2]
(
     column1
     ,column2
     ,column3
)

Open in new window


As you can see, I'm halfway there.  But I'm having trouble figuring out how to code the "select" segment that goes against the source_db.  Any help is appreciated.

Thanks,
Glen
jisoo411Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

chaauCommented:
It was tough, but doable:

Declare @Tables as Table
(
	TableName	Varchar(50)
);

insert into @Tables 
(TableName)
select TableName 
from
(        
		SELECT 'table1' as TableName       
		UNION ALL SELECT 'table2'							
)a

declare @SQL nvarchar(max);
declare @SQL2 nvarchar(max)='';

select
@SQL = COALESCE(@SQL + '
', '')
+ CASE WHEN ROW_NUMBER() OVER(PARTITION BY a.TableName ORDER BY c.column_id) = 1 and ROW_NUMBER() OVER(ORDER BY a.TableName, c.column_id) <> 1 THEN 
'		)

' 
ELSE ''
END
+ CASE WHEN ROW_NUMBER() OVER(PARTITION BY a.TableName ORDER BY c.column_id) = 1
	THEN @SQL2 +
		'
		INSERT INTO [target_db].[dbo].['+a.TableName+']
		( 
			['+c.name+']'
	ELSE
	'			,['+c.name+'] '
END,
@SQL2 = CASE WHEN ROW_NUMBER() OVER(PARTITION BY a.TableName ORDER BY c.column_id) = 1  THEN 
'' ELSE @SQL2 END,
@SQL2 = COALESCE(@SQL2 + '
', '')
+ CASE WHEN ROW_NUMBER() OVER(PARTITION BY a.TableName ORDER BY c.column_id) = 1
	THEN
		'
		SELECT	['+c.name+']'
	ELSE
	'			,['+c.name+'] '
END
+ CASE WHEN ROW_NUMBER() OVER(PARTITION BY a.TableName ORDER BY c.column_id desc) = 1 THEN 
'
		FROM [source_db].[dbo].['+a.TableName+']
' 
ELSE ''
END
FROM @Tables a
INNER JOIN sys.Objects o
on o.Name = a.TableName
INNER JOIN sys.Columns c
on c.object_id = o.object_id
INNER JOIN sys.Types t
on c.user_type_id = t.user_type_id
Where o.type = 'U'
ORDER BY a.TableName, c.column_id
SET @SQL = @SQL + 
'
		)
' + @SQL2
print @SQL

Open in new window

Produces this:

		INSERT INTO [target_db].[dbo].[table1]
		( 
			[column1]
			,[column2] 
			,[column3] 
		)



		SELECT	[column1]
			,[column2] 
			,[column3] 
		FROM [source_db].[dbo].[table1]

		INSERT INTO [target_db].[dbo].[table2]
		( 
			[column1]
			,[column2] 
			,[column3] 
		)


		SELECT	[column1]
			,[column2] 
			,[column3] 
		FROM [source_db].[dbo].[table2]

Open in new window

BTW, consider using QUOTENAME instead of ['+c.name+']' synatx, it will cater for some crazy cases where there is a '[' in the column name

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jisoo411Author Commented:
Perfect!  I was having trouble making that row number order by desc portion work myself, didn't stop to think about storing it into a 2nd variable.  Thanks!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.