Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 如何创建将一列中的值设置为另一个表中列的值的查询_Sql Server - Fatal编程技术网

Sql server 如何创建将一列中的值设置为另一个表中列的值的查询

Sql server 如何创建将一列中的值设置为另一个表中列的值的查询,sql-server,Sql Server,我是说我有一张桌子 table1 idbook idauthor title magazine 1 NULL title_1 magazine_1 2 2 title_2 magazine_2 还有一个 table2 idauthor name surname 1 name_1 surname_1 2 name_2 surname_2 我想写一个查询来更新表1,并将标题_1的值“i

我是说我有一张桌子

table1
idbook idauthor  title     magazine
 1       NULL   title_1   magazine_1
 2        2     title_2   magazine_2
还有一个

table2
idauthor   name     surname
   1      name_1   surname_1
   2      name_2   surname_2
我想写一个查询来更新表1,并将标题_1的值“idauthor”设置为与表2中名为_1的“idauthor”相同的值

会是什么样子?还是不可能


如何

我看不到
表1
表2
之间有匹配的列,我猜这个示例中缺少了一些内容。但是我将把它写出来,假设
table2
有一列
idbook
,它与
table1
匹配

update table1, table2
set table1.idauthor = table2.idauthor
where table1.idbook = table2.idbook

如果没有匹配的列,则无法进行更新。

实际上,公共列是idauthor,可以将其视为外键。但由于无法将表1的行与表2匹配,因此必须执行某种脏更新语句,这只适用于上面给出的示例,而不适用于其他场景

UPDATE table1 SET idauthor = (SELECT idauthor FROM table2 WHERE name LIKE "name_1" AND surname LIKE "surname_1") WHERE idauthor ISNULL;

此查询将更新表1中所有在idauthor列中有空值的行,并将其设置为您正在搜索的名为_1和姓为_1的行。

如果这两个表没有公共列,您如何连接它们<代码>更新table1,table2设置table1.idauthor=table2.idauthor,其中table2.name='name\u 1'。