将值从一个表插入到另一个表中

时间:2012-07-28 07:14:20

标签: sql sql-server sql-server-2008

我有2个表。所有ID都包含在表1中(Tbl_Distributor)。第二张表有所有名字。

我想根据id。

将所有名称添加到第一个表中

我的选择查询如下。

enter image description here

 INSERT INTO dbo.Tbl_Distributor(Giv_Name) where dealercode= a.dealercode

 SELECT a.dealercode,d.nameinfull  
 FROM dealerplacement a,dealer d
 where a.dealercode= d.dealercode
 order by a.dealercode ASC

这会返回nameinfulldealercode。我想将此nameinfull添加到Tbl_Distributor

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:2)

UPDATE R
SET Giv_Name = D.FirstName
FROM
   dbo.Tbl_Distributor R
   INNER JOIN dbo.Dealer D
      ON R.Dis_ID = D.DealerCode

答案 1 :(得分:-1)

你不能在这里使用INSERT。您需要使用更新。我会用游标做这样的任务。

declare @id int, @name varchar(1000)
DECLARE c CURSOR FOR
SELECT a.dealercode,d.nameinfull  
 FROM dealerplacement a,dealer d
 where a.dealercode= d.dealercode
 order by a.dealercode ASC

OPEN c

FETCH NEXT FROM c 
INTO @id, @name

WHILE @@FETCH_STATUS = 0
BEGIN

update Tbl_Distributor set Giv_Name = @name where dealercode = @id

FETCH NEXT FROM c 
INTO @id, @name
end

CLOSE c;
DEALLOCATE c;

另外,我在select语句中使用join:

SELECT a.dealercode,d.nameinfull  
FROM dealerplacement a inner join dealer d
on a.dealercode= d.dealercode
order by a.dealercode ASC