I have a lookup table with about 10 records, I know I can script the structure to a text file, but how can I script the data to insert into commands?
-
2What DBMS are you using?Nicolas Buduroi– Nicolas Buduroi2009-10-26 16:33:28 +00:00Commented Oct 26, 2009 at 16:33
-
1some sample data and a detailed description of what should happen to that data will get you a useful answer.dnagirl– dnagirl2009-10-26 16:33:43 +00:00Commented Oct 26, 2009 at 16:33
-
possible duplicate of Exporting data In SQL Server as INSERT INTOFlexo - Save the data dump– Flexo - Save the data dump ♦2011-12-31 04:03:17 +00:00Commented Dec 31, 2011 at 4:03
Add a comment
|
6 Answers
Assuming SQL Server...
SQL Management Studio will generate an insert script. Right-click your database and select Tasks-Export data
1 Comment
Madhivanan
Note that this is supported from version 2008 onwards
Do something like this:
select "insert into my_targ_table(my_field_1, my_field_2, ..., my_field_n) values(" || x.my_field_1_col || ", " || x.my_field_2_col || ");"
from my_source_table x
Then just run the script you've generated.
1 Comment
recursive
I had the same idea, only 28 seconds later.
This code works with all tables
DECLARE @TblName varchar(128)
DECLARE @WhereClause varchar(255)
DECLARE @cmd1 varchar(7000)
DECLARE @cmd2 varchar(7000)
SET @TblName = '<tablename>' --Name of your table
SET @WhereClause = ' ' --where clause ex columnA = 1
SET @cmd1 = 'SELECT '' INSERT INTO ' + @TblName + ' ( '
SET @cmd2 = ' + '' VALUES ( '' + '
create table #tableDef (id int identity (1,1), ColType int, ColName varchar(128))
--Fetch column names and datatypes
insert #tableDef (ColType, ColName)
select case when DATA_TYPE like '%char%' then 1
when DATA_TYPE like '%datetime%' then 2
else 0 end ,
COLUMN_NAME
from information_schema.columns
where TABLE_NAME = @TblName
order by ORDINAL_POSITION
SELECT @cmd1 = @cmd1 + ColName + ',',
@cmd2 = @cmd2
+ ' CASE WHEN ' + ColName + ' IS NULL '
+ ' THEN ''NULL'' '
+ ' ELSE '
+ case ColType
when 1 then ''''''''' + ' + ColName + ' + '''''''''
when 2 then ''''''''' + ' + 'CONVERT(VARCHAR(20),' + ColName + ')' + ' + '''''''''
else 'CONVERT(VARCHAR(20),' + ColName + ')' end
+ ' END + '','' + '
from #tableDef
order by id
select @cmd1 = left(@cmd1,len(@cmd1)-1) + ' ) '' '
select @cmd2 = left(@cmd2,len(@cmd2)-8) + '+'')'' FROM ' + @tblName + @WhereClause
select '/*' + @cmd1 + @cmd2 + '*/'
exec (@cmd1 + @cmd2)
drop table #tableDef