简体   繁体   中英

How to use identity column value of target table to insert in another column of same table

Pardon the title of question if it is confusing. Table E is source and Table S is target. S.SEA_ID is identity column (int, not null). Whenever those join conditions are NOT MATCHED AND E.ACCT_NUM IS NULL , I want to insert the value 'EY|' + CAST(S.SEA_ID AS VARCHAR) 'EY|' + CAST(S.SEA_ID AS VARCHAR) in column S.ACCT_NUM . But I am getting the error

The multi-part identifier "S.SEA_ID" could not be bound.

Is it possible to insert identity column value of target table to populate another column of the same target table? If it is not possible in below MERGE statement, what are my other options?

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);

I suggest that change ACCT_NUM Column as calculated column.

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

Also you can set this column in trigger.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM