Link to home
Start Free TrialLog in
Avatar of jisoo411
jisoo411

asked on

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
ASKER CERTIFIED SOLUTION
Avatar of chaau
chaau
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jisoo411
jisoo411

ASKER

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!