How to set a default value for one column in SQL based on another column

后端 未结 8 755
耶瑟儿~
耶瑟儿~ 2021-01-02 00:12

I\'m working with an old SQL 2000 database and I don\'t have a whole lot of SQL experience under my belt. When a new row is added to one of my tables I need to assign a defa

相关标签:
8条回答
  • 2021-01-02 00:49

    I can think of two ways:

    1. triggers
    2. default value or binding (this should work with a dependency)

    Triggers seem well explained here, so I won't elaborate. But generally I try and stay away from triggers for this sort of stuff, as they are more appropriate for other tasks

    "default value or binding" can be achieved by creating a function e.g.

    CREATE FUNCTION [dbo].[ComponentContractor_SortOrder] ()
    RETURNS float
    AS
    BEGIN
    RETURN (SELECT MAX(SortOrder) + 5 FROM [dbo].[tblTender_ComponentContractor])
    END
    

    And then setting the "default value or binding" for that column to ([dbo].ComponentContractor_SortOrder)

    0 讨论(0)
  • 2021-01-02 00:51

    Be sure to write the trigger so it will handle multi-row inserts. Do not process one row at a time in a trigger or assume only one row will be in the inserted table.

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