Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.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 选择入表_Sql_Sql Server_Tsql - Fatal编程技术网

Sql 选择入表

Sql 选择入表,sql,sql-server,tsql,Sql,Sql Server,Tsql,表A: ServerName, InstanceName, GroupName, Value1 (Some servers have more than 1 instance, therefore some servers are listed more than once) (400 records) 表B: ServerName, GroupName (100 records) 首先,我想将表B中的GroupName插入表B中存在ServerName的表A中。然后,我想从表A中删除没有G

表A:

ServerName, InstanceName, GroupName, Value1 (Some servers have more than 1 instance, therefore some servers are listed more than once) (400 records)
表B:

ServerName, GroupName (100 records)
首先,我想将表B中的
GroupName
插入表B中存在
ServerName
的表A中。然后,我想从表A中删除没有
GroupName
的所有服务器,以便在表A中只添加100条记录,并添加
GroupName

样本数据

表A:

ServerName      InstanceName     GroupName          Value1
----------------------------------------------------------
Server1         Instance 1        -                 500
Server1         Instance 2        -                 300
Server2         Instance 1        -                 400
表B:

ServerName      GroupName
-------------------------
Server1         Group1
Server2         Group2

因为每个表中有不同数量的记录,所以简单的
选择进入
不起作用。

首先您应该从表B更新
表a.GroupName
。尝试使用以下方法:

update A
set    A.GroupName = B.GroupName
from   TableA TAB
       inner join TableB B on A.ServerName = B.ServerName
where  ISNULL(A.GroupName,'-') = '-';
GO
然后,您可以删除所有没有
GroupName

delete from TableA where ISNULL(GroupName,'-') = '-';
GO

在前面的回答中,更新查询很好,但删除一次可以进行更多修改

UPDATE TA
SET    TA.GroupName = TB.GroupName
FROM   TableA TA
       INNER JOIN TableB TB ON TA.ServerName = TB.ServerName

DELETE TA
FROM   TableA TA
WHERE TA.ServerName NOT IN(SELECT ServerName FROM TableB)

不同数量的记录?你的意思是不同的列数吗?那么,你想更新表A吗?