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

如何快速选择sql部分连续字段插入到新表中
如想将B表的数据插入到A表。但不是全部的字段,而是一部分连续字段,在平时插入时总是一个字段一个字段的输入和选择,相当麻烦,有什么好办法吗?
如A表 字段1,字段2,字段3,字段4,。。。字段N
而B表 字段1,字段2,字段3,字段4,。。。字段N
常规情况下的插入是
SQL code
[code=SQL]

insert into a (字段4,。。。字段N) 
select 字段4,。。。字段N from b
[code=SQL][/code][/code]这些在表中的不是全部的但相对连续的字段,有什么快速方法选择吗?

------解决方案--------------------
SQL code
DECLARE @表的前n个字段 int,@ColList varchar(200)
SET @表的前n个字段=5
SELECT @ColList=ISNULL(@ColList+',','')+QUOTENAME(name) 
FROM syscolumns 
WHERE id=OBJECT_ID('dbo.Employees') 
    and colid<=@表的前n个字段
EXEC('SELECT '+@ColList+' FROM dbo.Employees')
/*
EmployeeID  LastName             FirstName  Title                          TitleOfCourtesy
----------- -------------------- ---------- ------------------------------ -------------------------
1           Davolio              Nancy      Sales Representative           Ms.
2           Fuller               Andrew     Vice President, Sales          Dr.
3           Leverling            Janet      Sales Representative           Ms.
4           Peacock              Margaret   Sales Representative           Mrs.
5           Buchanan             Steven     Sales Manager                  Mr.
6           Suyama               Michael    Sales Representative           Mr.
7           King                 Robert     Sales Representative           Mr.
8           Callahan             Laura      Inside Sales Coordinator       Ms.
9           Dodsworth            Anne       Sales Representative           Ms.

(9 行受影响)
*/