我有2个表。所有ID都包含在表1中(Tbl_Distributor
)。第二张表有所有名字。
我想根据id。
将所有名称添加到第一个表中我的选择查询如下。
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
这会返回nameinfull
和dealercode
。我想将此nameinfull
添加到Tbl_Distributor
。
请帮我解决这个问题。
答案 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