sql将特定列从一个表复制到另一个表

时间:2013-12-27 07:14:58

标签: sql-server database

sql server 中,我在DevDB中有一个代码表。它有10列。 外键列为ParentCodeID int列

我需要将除 int 列以外的5列复制到TestDB。但我需要在此专栏中加入“33”作为ParentcodeID

250+条记录。我需要自动执行此操作。 请帮忙!!!!

2 个答案:

答案 0 :(得分:0)

试试这个,

INSERT INTO TestDB.dbo.Codes(Col1,Col2,Col3,....)
SELECT 33,col1,col2.... FROM DevDB.dbo.tblCode where ParentCodeID = xx

答案 1 :(得分:0)

如果要添加新列,您甚至可以自动生成脚本以避免将来进行更正。这是代码:

declare @tblName varchar(100),@FieldList varchar(max),@FieldListReplaced varchar(max),@sql varchar(max),@Field varchar(100),@ReplacedField varchar(100),@ReplaceWithValue varchar(100)

set @tblName='Codes'
set @ReplacedField='ParentcodeID'
set @ReplaceWithValue='33'
set @FieldList=','

declare cur_fieldlist cursor for 
select [Name] from sys.all_columns 
where object_id=(Select id from sysobjects where name=@tblName) and 
      is_computed=0 and (is_identity=0) 
order by column_id
open cur_fieldlist
fetch next from cur_fieldlist into @Field
while @@fetch_status = 0
begin
 set @FieldList=@FieldList+@Field+','
 fetch next from cur_fieldlist into @Field
end
close cur_fieldlist
deallocate cur_fieldlist

set @FieldListReplaced=replace(@FieldList,','+@ReplacedField+',',','+@ReplaceWithValue+',') /*to avoid replacement for several fields like ParentcodeID, ParentcodeID2, BigParentcodeID, BigParentcodeID2 etc. */
set @FieldList=substring(@FieldList,2,(len(@FieldList)-2))
set @FieldListReplaced=substring(@FieldListReplaced,2,(len(@FieldListReplaced)-2))

set @sql='INSERT INTO TestDB.dbo.'+@tblName+' ('+@FieldList+')
SELECT '+@FieldListReplaced+' FROM DevDB.dbo.'+@tblName+' WHERE 1=1 /* put your conditions here */'

print (@sql) --for checking

exec (@sql)