Referencing another column in DEFAULT definition in SQL Server 2005

后端 未结 1 512
心在旅途
心在旅途 2021-01-21 01:34

I want to define a column in my table with following requirements:

  1. The column should be insertable. If the value is provided in the INSERT statement, then it shoul
相关标签:
1条回答
  • 2021-01-21 01:58

    Here you go, I'm demonstrating this with an example schema since you've not provided your real table/column names.

    Table:

    CREATE TABLE test
      (
         id   INT NOT NULL PRIMARY KEY IDENTITY, --made up key
         col1 INT, --first column to add, wasn't sure if this was nullable or not
         col2 INT, --second column to add, wasn't sure if this was nullable or not
         col3 INT NOT NULL --this is the column to optionally insert into
      ) 
    

    Here is the trigger definition:

    CREATE TRIGGER demo
    ON test
    INSTEAD OF INSERT
    AS
        INSERT INTO test (col1,col2,col3)
        SELECT inserted.col1,
               inserted.col2,
               CASE
                 WHEN inserted.col3 IS NULL THEN COALESCE(inserted.col1, 0) + COALESCE(inserted.col2, 0)
                 ELSE inserted.col3
               END
        FROM   inserted
    

    Basically it replaces any insert statement done on the table with the one in the trigger, so I check using the inserted temporary table to see if the value that is trying to be inserted into our non-nullable optional column, col3, is NULL. If it is, I replace it with the addition of col1 and col2 (I'm coalescing with zero as you didn't mention if the two source columns are nullable or not).

    You can then run insert statements which either include it or not, despite the fact col3 is not nullable:

    INSERT INTO test(col1,col2)
    SELECT 12, 31
    GO
    
    INSERT INTO test(col1, col2, col3)
    SELECT 1, 2, 89
    GO
    

    Results are:

    ID  COL1 COL2 COL3
    ------------------  
    1   12   31    43
    2   1    2     89
    

    If the trigger wasn't there, you could have got an error trying to run that first insert statement, telling you it couldn't insert NULL into col3.

    Notice also that the second insert statement that specifies a value has not been replaced by the addition, as requested.

    Here's a working SQL Fiddle.

    0 讨论(0)
提交回复
热议问题