日期:2014-05-18  浏览次数:20459 次

在线等一个简单问题:表字段映射
两张表:
table1(a   int,b   varchar(10),c   datetime,d   char(10))
table2(a1   int,b1   varchar(10),c1   datetime)
把table1的a,b,c字段内容加载到table2中,需经过字段映射:a→a1,b→b1,c→c1
可以用以下方法映射:
select   a   as   a1,b   as   b1,c   as   c1   into   table2
from   table1
问题:
若table1的字段比较多,而且是从字符串中读取的(比如读取为 'a,b,c,d '),用此映射方法似乎比较麻烦,哪位有更好的办法?


------解决方案--------------------
--如果table2是生成的話


Create Table table1(a int,b varchar(10),c datetime,d char(10), e char(10))
GO
Declare @S Varchar(8000)
Select @S = ' '
Select @S = @S + ', ' + Name + ' As ' + Name + '1 ' From SysColumns Where ID = OBJECT_ID( 'table1 ') Order By ColID
Select @S = 'Select ' + Stuff(@S, 1, 1, ' ') + ' into table2 from table1 '
EXEC(@S)

Select * From table2
GO
Drop Table table1, table2
--Result
/*
a1 b1 c1 d1 e1
*/

------解决方案--------------------
这样试试:
declare @SourceFieldList varchar(100),@DestiFieldList varchar(100)
set @SourceFieldList = 'a,b,c '
set @DestiFieldList = 'a1,b1,c1 '
EXEC( 'insert into table2( ' + @DestiFieldList + ') select ' + @SourceFieldList + ' from table1 ')

------解决方案--------------------
declare @sql varchar(8000)
declare @str varchar(100)
inser table2 (a1,b1,c1)
set @sql = 'select ' + 'left(@字符串,5) ' + 'into table2 from table1 '
exec(@sql)