我有一个存储过程,它有一个merge .. into语句。我试图从存储过程中获取主键的值。
SET @NewCompanyID = @CompanyID
....
merge company as c
using ( select @CompanyID) as compAlt (company_id )
on compAlt.company_id = c.company_id
when matched
then
update set ....
when not matched
then
insert ... ;
SET @NewCompanyID = @@identity;
如果merge语句运行更新,我想将@NewCompanyID设置为传递给存储过程(@CompanyID)的任何值。如果执行了insert语句,那么我想传递@@ identity。我该怎么做?
答案 0 :(得分:0)
我在合并之前添加了
DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));
然后
OUTPUT $action INTO @SummaryOfChanges;
SELECT @Change = Change
FROM @SummaryOfChanges; /* there is always one update or insert */
IF @Change = 'INSERT'
BEGIN
....
END
这很好。