How do you add a NOT NULL FOREIGN KEY column to an existing (populated) table in MS SQL?

后端 未结 2 2204
误落风尘
误落风尘 2021-02-20 14:36

I need to add a NOT NULL column to an existing (populated) table that will be a foreign key to another table. This brings about two problems:

  1. When you add the c

相关标签:
2条回答
  • 2021-02-20 14:57

    Create the column, but allow NULL. Populate the column with the correct data from the foreign key table. Alter the column add not null. Add the foreign key constraint.

    0 讨论(0)
  • 2021-02-20 15:13

    About parts of your questions (ofc after years):

    1.If you mean that the default value would be something so smart, and you wouldn`t need to change it in future, then your wish is wrong. why?

    for two reasons:

    • a) In the concept of Default value (in every where programming
      languages, DBs and so on...) the default value is not something which replace the value dynamically with something you want. For example Func Sum(a,b,c=10), in this situation if you don't enter parameter c, it would take it as 10, otherwise you should enter
      something instead. so default values are predictable and calculable
      values, NOT smart values.
    • b) Foreign keys are something even more sensitive than a optional
      parameter in a method, coz of the relational meanings in RDBMSs so u surely should edit that in future, even maybe sometimes it change
      over and over base on usages of DB.

    2.It can be handle with the code i`ll show you.

    Therefore base on this explanations you could have a column with default value which exist in Fkeys, but it won`t be something you need, and you should update it in future base on your usage. and for this you need:

    FIRST:

    • Create a function that return a valid and exist foreign key of specific table like this:
    CREATE FUNCTION SelectMinForeignKey()
    RETURNS INT
    AS
    BEGIN
      DECLARE @FirstID INT
      SELECT @FirstID = MIN(ID) from DetailTableExample01
      RETURN @FirstID
    END
    

    SECOND:

    • Then you should alter your table to add column like this:
    ALTER TABLE example1 ADD NoNullableCol INT NOT NULL DEFAULT [dbo].SelectMinForeignKey()
    
    • or with adding Relation instantly:
      ALTER TABLE example1 
        ADD NoNullableCol2 INT NOT NULL  DEFAULT [dbo].SelectMinForeignKey() ,
        FOREIGN KEY(NoNullableCol2) REFERENCES DetailTableExample01(id);
    
    • or more complete with adding constraint instantly and assignable FK name:
    ALTER TABLE dbo.example1 ADD
        NoNullableCol INT NOT NULL  DEFAULT [dbo].SelectMinForeignKey(),
        CONSTRAINT FK_example1_DetailTableExample01
        FOREIGN KEY (NoNullableCol) 
        REFERENCES dbo.DetailTableExample01 (ID) 
         ON UPDATE  CASCADE 
         ON DELETE  CASCADE;
    
    • or:
    ALTER TABLE dbo.example1 ADD
        NoNullableCol INT NOT NULL  DEFAULT [dbo].SelectMinForeignKey()
    GO
    ALTER TABLE dbo.example1 ADD 
        CONSTRAINT FK_example1_DetailTableExample01
        FOREIGN KEY (NoNullableCol) 
        REFERENCES dbo.DetailTableExample01 (ID) 
         ON UPDATE  CASCADE 
         ON DELETE  CASCADE
    

    NOTE: As you know table and column names are sample.

    THIRD:

    • Now you should change values in NoNullableCol as you want

    All-in-One:

    • The entire query would be something like this
    CREATE FUNCTION SelectMinForeignKey()
    RETURNS INT
    AS
    BEGIN
      DECLARE @FirstID INT
      SELECT @FirstID = MIN(ID) from DetailTableExample01
      RETURN @FirstID
    END
    
    GO
    
    ALTER TABLE dbo.example1 ADD
        NoNullableCol INT NOT NULL  DEFAULT [dbo].SelectMinForeignKey(),
        CONSTRAINT FK_example1_DetailTableExample01
        FOREIGN KEY (NoNullableCol) 
        REFERENCES dbo.DetailTableExample01 (ID) 
         ON UPDATE  CASCADE 
         ON DELETE  CASCADE;
    

    AND It`s Done!

    Hope it solve your problem

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