How to insert default values in SQL table?

前端 未结 8 908
灰色年华
灰色年华 2020-11-28 06:26

I have a table like this:

create table1 (field1 int,
               field2 int default 5557,
               field3 int default 1337, 
               field4 i         


        
相关标签:
8条回答
  • 2020-11-28 06:51

    Try it like this

    INSERT INTO table1 (field1, field3) VALUES (5,10)
    

    Then field2 and field4 should have default values.

    0 讨论(0)
  • 2020-11-28 06:53
    CREATE PROC SP_EMPLOYEE                             --By Using TYPE parameter and CASE  in Stored procedure
    (@TYPE INT)
    AS
    BEGIN
    IF @TYPE=1
    BEGIN
    SELECT DESIGID,DESIGNAME FROM GP_DESIGNATION
    END
    IF @TYPE=2
    BEGIN
    SELECT ID,NAME,DESIGNAME,
    case D.ISACTIVE when 'Y' then 'ISACTIVE' when 'N' then 'INACTIVE' else 'not' end as ACTIVE
     FROM GP_EMPLOYEEDETAILS ED 
      JOIN  GP_DESIGNATION D ON ED.DESIGNATION=D.DESIGID
    END
    END
    
    0 讨论(0)
  • 2020-11-28 06:56

    You can write in this way

    GO
    ALTER TABLE Table_name  ADD
    column_name decimal(18, 2) NOT NULL CONSTRAINT Constant_name DEFAULT 0
    GO
    ALTER TABLE Table_name SET (LOCK_ESCALATION = TABLE)
    GO
    COMMIT
    
    0 讨论(0)
  • 2020-11-28 07:01

    To insert the default values you should omit them something like this :

    Insert into Table (Field2) values(5)
    

    All other fields will have null or their default values if it has defined.

    0 讨论(0)
  • 2020-11-28 07:02

    If your columns should not contain NULL values, you need to define the columns as NOT NULL as well, otherwise the passed in NULL will be used instead of the default and not produce an error.

    If you don't pass in any value to these fields (which requires you to specify the fields that you do want to use), the defaults will be used:

    INSERT INTO 
      table1 (field1, field3) 
    VALUES   (5,10)
    
    0 讨论(0)
  • 2020-11-28 07:07

    Best practice it to list your columns so you're independent of table changes (new column or column order etc)

    insert into table1 (field1, field3)  values (5,10)
    

    However, if you don't want to do this, use the DEFAULT keyword

    insert into table1 values (5, DEFAULT, 10, DEFAULT)
    
    0 讨论(0)
提交回复
热议问题