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

后端 未结 8 711
耶瑟儿~
耶瑟儿~ 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:28

    So, for example, in a TAG table (where tags are applied to posts) if you want to count one tag as another...but default to counting new tags as themselves, you would have a trigger like this:

    CREATE TRIGGER [dbo].[TR_Tag_Insert]
       ON  [dbo].[Tag]
       AFTER INSERT
    AS 
    BEGIN
       SET NOCOUNT ON;
    
       UPDATE dbo.Tag 
       SET [CountAs] = I.[ID]
       FROM INSERTED AS I
       WHERE I.[CountAs] IS NULL
       AND dbo.Tag.ID = I.ID
    END
    
    0 讨论(0)
  • 2021-01-02 00:32

    Use a trigger as suggested by Stephen Wrighton:

    CREATE TRIGGER [myTable_TriggerName] ON dbo.myTable FOR INSERT        
    AS
    SET NOCOUNT ON
    UPDATE myTable
    SET
        timeValue = '2 hours' -- assuming string values
    where ID in (
        select ID
        from INSERTED
        where
            timeValue = ''
            AND workCategory = 'A'
    )
    
    0 讨论(0)
  • 2021-01-02 00:35

    Yeah, trigger.

    Naturally, instead of hard-coding the defaults, you'll look them up from a table.

    Expanding on this, your new table then becomes the work_category table (id, name, default_hours), and you original table maintains a foreign key to it, transforming fom (id, work_category, hours) to (id, work_category_id, hours).

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

    Generally I steer away from triggers. Almost all dbms have some sort of support for constraints.

    I find them easier to understand , debug and maintain.

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

    If what you are looking for is to define a column definition based on another column you can do something like this:

    create table testable 
    (
        c1 int, 
        c2 datetime default getdate(), 
        c3 as year(c2)
    );
    
    insert into testable (c1) select 1
    
    select * from testable;
    

    Your result set should look like this :

    c1 | c2                      | c3
    1  | 2013-04-03 17:18:43.897 | 2013
    

    As you can see AS (in the column definition) does the trick ;) Hope it helped.

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

    I would use a trigger on Insert.

    Just check to see if a value has been assigned, and if not, go grab the correct one and use it.

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