问题信息
详细问题
我解释问题的最好方法就是解释我想要的结果。我正在尝试获取一组特定的办公室,将其数据插入 dbo.DeliveryLocation 表中,然后获取输出 inserted.DeliveryLocationId 并更新相应办公室的 DeliveryLocationId 字段使用该 ID。
期望结果示例
之前的 Office 数据
OfficeId | DeliveryLocationId
-----------------------------
1 | null
2 | null
3 | null
Run the SQL statement
之后的 Office 数据
OfficeId | DeliveryLocationId
-----------------------------
1 | 5
2 | 6
3 | 7
DeliveryLocationId 为 5 的送货位置的创建方式为 OfficeId为1的Office的数据
DeliveryLocationId 为 6 的送货位置是通过以下方式创建的 OfficeId为2的Office的数据
DeliveryLocationId 为 7 的送货位置的创建方式为 OfficeId为3的Office数据
问题
根据下面我当前的 SQL 脚本,您可以看到我已完成第一部分(将 Office 数据插入到“交付位置”表中)。第二部分(使用创建的交付位置的相应 DeliveryLocationId 更新 Office)尚未完成,我不确定如何去做。
我最初的想法/解决方案
如果有一种方法来存储相关的 OfficeId 和 DeliveryLocationId,也许我们可以循环遍历它们并在第二个 SQL 语句中更新办公室,而不是尝试创建一个执行所有操作的 SQL 语句。
引用文献
dbo.DeliveryLocation
[DeliveryLocationId] [int] IDENTITY(1,1) NOT NULL,
[LocationName] [nvarchar](max) NULL,
[ShortName] [nvarchar](max) NULL,
[ValidatedAddressId] [int] NOT NULL,
[DropoffInstruction] [nvarchar](max) NULL,
[PickupInstruction] [nvarchar](max) NULL,
[TaxRate] [decimal](18, 2) NOT NULL,
[Active] [bit] NOT NULL,
[DisableOffices] [bit] NOT NULL
dbo.Office
[OfficeId] [int] IDENTITY(1,1) NOT NULL,
[OfficeName] [nvarchar](max) NULL,
[ValidatedAddressId] [int] NOT NULL,
[ReferralSource] [nvarchar](max) NOT NULL,
[NumberOfEmployees] [int] NOT NULL,
[DeliveryLocationId] [int] NULL
当前 SQL
insert into
dbo.DeliveryLocation
(LocationName, ShortName, ValidatedAddressId, Active, DisableOffices)
output
inserted.DeliveryLocationId
select
OfficeName, OfficeName, ValidatedAddressId, 0, 0
from
dbo.Office as o
where
OfficeId in
(
select distinct
OfficeId
from
dbo.[User] as u
where
u.DeliveryLocationId is null
and
u.OfficeId is not null
)
最佳答案
我不确定是否在 INSERT
语句中执行此操作,但如果您使用 Office(或基于 Office 的查询)作为源的 MERGE
语句,您将能够在 OUTPUT
子句中引用 source.OfficeId 以及inserted.DeliveryLocationId。您可以简单地跳过 MERGE
的更新和删除用法,而仅使用 ON NOT MATCHED
子句。
当我做这样的事情时,我将输出放入临时表中,然后从那里执行我需要做的任何进一步更新或插入。
如果您以前没有使用过MERGE
语句(或者甚至对于没有使用过其所有功能的人),这是一个关于如何使用它们的非常好的资源,以及如何很好地使用它们:http://www.made2mentor.com/2012/07/got-the-urge-to-merge/
关于SQL - 如何使用插入的输出来更新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30761456/