为什么SQL中的'insert into select'语句作为新行插入,而不能正确插入?

问题描述 投票:-1回答:1

我有一个表1。

enter image description here

我有另一个空表2,表2的列数如下。

enter image description here

我想通过从表1中选择插入到表2中--所以我把查询写成。

insert into table2(employee,id,zone,url) 
select employee, id, zone, concat('https://',employee,'.com/',id,'?',zone) 
from table1

现在我的表2是这样的:

enter image description here

现在说说 authcode 列,我做了以下操作并将其插入到table2中。

insert into table2(authcode) 
SELECT CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(URL,8,100)),2) 
from table2.

但插入的情况不同,像这样作为一个全新的行集。

enter image description here

谁能帮助我将最后一列插入到相应的行中,而不是创建一个新的行?

sql sql-server database sql-insert
1个回答
4
投票

你应该做的是UPDATE表来填充列的内容 authcode但你可以在插入行的时候一步完成。

insert into table2(employee,id,zone,url, authcode) 
select 
  employee, 
  id, 
  zone, 
  concat('https://',employee,'.com/',id,'?',zone),
  CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(concat('https://',employee,'.com/',id,'?',zone),8,100)),2) 
from table1

或者如果你想更新的话

update table2
set authcode = CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(URL,8,100)),2) 
where authcode is null 

2
投票

你现在看到的结果是一个预期的行为 插入 语句。它总是会插入新的记录。

如果你想修改现有的记录,你需要使用一个叫做 更新 语句。

你可以把INSERT修改成像@forpas发布的那样,一步到位。另一种方法是将第二个INSERT修改为UPDATE,就像下面这样。

update table2
set authcode = CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(URL,8,100)),2)
© www.soinside.com 2019 - 2024. All rights reserved.