Sql 选择入表
表A: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
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吗?