Search code examples
sqlsql-serverdefault-constraint

SQL Server DEFAULT FOR Syntax


Why is there a syntax error near 'for' as SQL Server 2012 reports?

Is not DEFAULT FOR syntax available when creating a table, but when altering it? Here is a tutorial about altering a table and adding a default constraint link, but I can't get it right when creating it.

CREATE TABLE Meal (
    MealID int IDENTITY PRIMARY KEY,
    MealName varchar(50) NOT NULL,
    IsVege char NOT NULL,
    MealDescription varchar(150) NOT NULL,

    CONSTRAINT Ckh_Meal_IsVege
        CHECK (IsVege in ('t', 'f')),
    CONSTRAINT Def_Meal_IsVege
        DEFAUlT ('t') FOR IsVege,
);

Solution

  • It's a quirk of the CREATE TABLE syntax that you can only declare a DEFAULT constraint inline, as per StuartLC's answer. You can also create table constraints, but these are only:

    < table_constraint > ::=
    [ CONSTRAINT constraint_name ] 
    { 
        { PRIMARY KEY | UNIQUE } 
            [ CLUSTERED | NONCLUSTERED ] 
            (column [ ASC | DESC ] [ ,...n ] ) 
            [ 
                WITH FILLFACTOR = fillfactor 
               |WITH ( <index_option> [ , ...n ] ) 
            ]
            [ ON { partition_scheme_name (partition_column_name)
                | filegroup | "default" } ] 
        | FOREIGN KEY 
            ( column [ ,...n ] ) 
            REFERENCES referenced_table_name [ ( ref_column [ ,...n ] ) ] 
            [ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ] 
            [ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ] 
            [ NOT FOR REPLICATION ] 
        | CHECK [ NOT FOR REPLICATION ] ( logical_expression ) 
    }