如何使用目标表的标识列值插入同一个表的另一列

时间:2014-07-28 02:18:29

标签: sql sql-server insert merge identity-column

如果令人困惑,原谅问题的标题。表E是源,表S是目标。 S.SEA_ID是标识列(int,not null)。只要这些加入条件为NOT MATCHED AND E.ACCT_NUM IS NULL,我就想在'EY|' + CAST(S.SEA_ID AS VARCHAR)列中插入值S.ACCT_NUM。但是我收到了错误

  

多部分标识符" S.SEA_ID"无法受约束。

是否可以插入目标表的标识列值来填充同一目标表的另一列?如果在MERGE语句下面不可能,我的其他选择是什么?

MERGE INTO STG_EXTERNAL_ACCT S
USING ##EYDUPLICATES E
            ON E.COUNTERPARTY_NAME = S.COUNTERPARTY_NAME
            AND E.COUNTERPARTY_ADDRESS = S.COUNTERPARTY_ADDRESS
            AND E.COUNTERPARTY_STATE = S.COUNTERPARTY_STATE
            AND E.COUNTERPARTY_COUNTRY = S.COUNTERPARTY_COUNTRY
            AND E.COUNTERPARTY_CITY = S.COUNTERPARTY_CITY
WHEN NOT MATCHED AND ISNULL(E.ACCT_NUM,'')='' 
     THEN INSERT (ACCT_NUM, COUNTERPARTY_NAME, COUNTERPARTY_ADDRESS,
                  COUNTERPARTY_STATE, COUNTERPARTY_COUNTRY, COUNTERPARTY_CITY) 
          VALUES ('EY|' + CAST(S.SEA_ID AS VARCHAR),E.COUNTERPARTY_NAME,
                  E.COUNTERPARTY_ADDRESS, E.COUNTERPARTY_STATE, 
                  E.COUNTERPARTY_COUNTRY, E.COUNTERPARTY_CITY);

1 个答案:

答案 0 :(得分:0)

我建议将ACCT_NUM列更改为计算列。

ALTER Table STG_EXTERNAL_ACCT ALTER Column ACCT_NUM as 'EY|'+CAST(S.SEA_ID AS VARCHAR)

您也可以在触发器中设置此列。

Create Trigger TiggerName ON STG_EXTERNAL_ACCT 
INSTEAD OF INSERT
AS Begin
  Insert Into STG_EXTERNAL_ACCT (ACCT_Num, ...)
  Select 'EY|'+CAST(S.SEA_ID AS VARCHAR), ...
  From Inserted
End