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

sql中一个表的数据插入到另一个表中sql语句怎么写?谢谢!
A表有ID,NAME,AGE,三列,且ID是主键且不是自动增长列
B表有NAME和AGE两列,NAME是主键
现在要把B表所有记录插入到A表中,
sqs语句怎么写?谢谢!

------解决方案--------------------
SQL code

INSERT INTO A
SELECT Name,Age
FROM B

------解决方案--------------------
SQL code

DECLARE @ID INT
SET @ID=1
DECLARE @COUNT INT
SELECT @COUNT =COUNT(1) FROM B
WHILE @ID<=@COUNT
BEGIN
   INSERT INTO A SELECT @ID,NAME,Age from B
  SET @ID=@ID+1
END

------解决方案--------------------
declare @id int
set @id=select id from A
insert into A select isnull(max(@id),0),* from B
就这样的思路吧
------解决方案--------------------
SQL code

INSERT INTO A
SELECT rn=ROW_NUMBER()over(order by Name),Name,Age
FROM B

------解决方案--------------------
SQL code
-- 取出最大ID
declare @maxID int
select @maxID = max(ID) from A
-- 插入数据
insert into A(ID, Name, AGE)
select ID=(row_number() over (order by Name))+@MaxID, Name, Age from B

------解决方案--------------------
给你个结果
SQL code

CREATE TABLE A
(
    ID INT NOT NULL,
    Name VARCHAR(100),
    age INT
)
GO
CREATE TABLE B
(
    Name VARCHAR(100),
    Age INT
)
GO

INSERT INTO B
SELECT 'haha',3 UNION
SELECT 'hoho',3 UNION
SELECT 'hehe',3


INSERT INTO A
SELECT rn=ROW_NUMBER()over(order by Name),Name,Age
FROM B

SELECT * FROM A

ID    Name    age
1    haha    3
2    hehe    3
3    hoho    3

------解决方案--------------------
若表A中已存在数据,则使用下面的语句
SQL code

INSERT INTO A
SELECT rn=ROW_NUMBER()over(order by Name) + (SELECT MAX(Id) FROM A),Name,Age
FROM B