【问题标题】:Find Identity when using Merge使用合并时查找身份
【发布时间】:2013-11-19 17:16:48
【问题描述】:

对不起,如果这是一个骗局,我看了大约 8 个问题,但没有完全解释我在寻找什么。

目标表 (dTable) aID bigint 身份 bID bigint(主键)

@JSON 表 @版本表

Merge into dTable t
using (select bid from @JSON) s
on t.bid = s.bid
when not matched
then insert(bid)
values (s.bid)
when matched
then update
set bid = s.bid

output
'dTable', @versionDate, action, inserted.bid, s.aid, @userid
into @version (tablename, versiondate, actiontaken, value, pk, userid)
;

希望获取 dTable 的标识字段,其中更新了值或添加了标识。

s.aid 返回一个空值,我想我必须做类似 isnull(inserted.aid, @@identity) 的事情。由于项目的规模和我的前任......我没有太多的测试环境。

试过@@Identity、scope_identity,感觉不到爱。

编辑:AID 表示我想要阻止的身份,如果值不存在 IE:ColumnName (BID),则添加 BID(人类可读文本的 bigint 值),从而创建新的 columnID (AID)。出于版本控制的目的,我想知道 AID,因为此 AID 将关联(FK)到其他表,如 _order、_enabled、_unit、_type。

【问题讨论】:

  • s. 别名从何而来?它没有在任何地方定义......
  • 已编辑代码。合并到 t(对于目标),使用 () s(对于源)
  • 输出子句中有一个未闭合的引号,不清楚它应该在哪里关闭,并且您正在插入列bid,但在您的dTable 定义中没有bid。

标签: sql tsql merge output identity


【解决方案1】:

试试你的 OUTPUT 子句:

output 'dTable', @versionDate, action, inserted.bid, inserted.AID, @userid
into @version

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多