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 t开发者_开发百科o insert into commands?
Ten records, and it's urgent?
Just type it out manually. Should be pretty easy to cut-n-paste.
Assuming SQL Server...
SQL Management Studio will generate an insert script. Right-click your database and select Tasks-Export data
This depends pretty much on the tools you are using...
The quick and dirty way is to run a select into a string and tell sql enterprise manager to give you text (not grid) as the output
SELECT 'INSERT INTO TABLES (fields here) VALUES (' + field1 + ', '....
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.
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
精彩评论