如何使用 TSQL 脚本将一个表拆分为另一个表

How can I split off one table into another table using TSQL script(如何使用 TSQL 脚本将一个表拆分为另一个表)
本文介绍了如何使用 TSQL 脚本将一个表拆分为另一个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

到目前为止我有这个代码:

I have this code so far:

DECLARE @AddressIDS TABLE
(
    AddressID int
)

INSERT INTO Address(Street1, City, StateCode, ZipCode)
OUTPUT inserted.AddressID INTO @AddressIDS
SELECT Street1, City, StateCode, ZipCode
    FROM Contact

现在我需要将 @AddressIDS 中的 ID 放回到 Contact 表的 AddressID 中.

Now I need to put the IDs in the @AddressIDS back into the AddressID of the Contact table.

这更好地描述了我在 TSQL 中尝试做的事情:

This better describes what I'm trying to do in TSQL:

推荐答案

假设 Street1 + City + StateCode + ZipCode 是唯一的,或者多个联系人可以共享同一个 AddressID,那么您就不需要推测 AddressID 值在一个中间步骤.您只需执行插入地址,然后:

Assuming Street1 + City + StateCode + ZipCode is unique, or that multiple contacts can share the same AddressID, then you don't need to suss out the AddressID values in an intermediate step. You can just perform your insert into Address and then:

UPDATE c 
  SET AddressID = a.AddressID
  FROM dbo.Contact AS c
  INNER JOIN dbo.Address AS a
  ON c.Street1 = a.Street1
  AND c.City = a.City
  AND c.StateCode = a.StateCode 
  AND c.ZipCode = a.ZipCode;

这篇关于如何使用 TSQL 脚本将一个表拆分为另一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)
sql group by versus distinct(sql group by 与不同)
How to return a incremental group number per group in SQL(如何在SQL中返回每个组的增量组号)
Count number of records returned by group by(统计分组返回的记录数)