gpt4 book ai didi

sql - 在 SQL Server 中更新查询后插入

转载 作者:行者123 更新时间:2023-12-04 23:47:27 26 4
gpt4 key购买 nike

我有一个存储在存储过程中的更新查询。

我想在执行存储过程后立即插入更新的查询。这是我的存储过程。

ALTER PROCEDURE [dbo].[sp_assign_account]
@id_agency int,
@month nvarchar(2),
@regional nvarchar(20),
@top int,
@assigned_by nvarchar(20)
AS
BEGIN
SET NOCOUNT ON;

UPDATE [AMAS].[dbo].[tbl_sample]
SET id_agency = @id_agency,
status = 'assigned',
stage = 'STA',
tgl_assign = GETDATE(),
assigned_by = @assigned_by
WHERE id_sample IN (SELECT TOP (@top) a.id_sample
FROM [AMAS].[dbo].[tbl_sample] a
LEFT JOIN mysystem.lapkeu.dbo.groupbranch b ON a.branch_id = b.BranchID
WHERE a.is_delete = '0'
AND a.status = 'not assigned'
AND a.stage = 'AMA'
AND MONTH(a.insert_at) = @month
AND a.branch_id IN (SELECT branch_id
FROM mysystem.lapkeu.dbo.groupbranch
WHERE GroupBranchID IN (SELECT b.group_branch_id
FROM [AMAS].[dbo].[tbl_collector_agency] a
JOIN [AMAS].[dbo].[tbl_area_collector] b ON a.id_collector = b.id_collector
WHERE a.id_agency = @id_agency)
)
ORDER BY NEWID()
)

// can i put insert query here??
END

或者我可以获得更新后的 ID?因为我使用的是随机数据更新,所以更新前没有初始化id。

最佳答案

您可以使用 Output clause 来实现它作为@Dale K 的评论

DECLARE @Updated table(id_agency int, .. // Any property as you want)

UPDATE [AMAS].[dbo].[tbl_sample] SET id_agency = @id_agency, status = 'assigned', stage='STA', tgl_assign = getdate(), assigned_by = @assigned_by
OUTPUT deleted.id_agency // Any property as you want
INTO @Updated
WHERE id_sample
IN (////)

SELECT * FROM @Updated

@Updated结果,你可以做你想做的事:InsertSelect,等

阅读以下教程以更好地理解。

https://www.sqlservercentral.com/articles/the-output-clause-for-update-statements

示例

enter image description here

关于sql - 在 SQL Server 中更新查询后插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59833989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com