Search code examples
sqlsql-serverdatabase-table

Creating tables in SQL server adding Constraints and Defaults


Hi i'm relatively new to SQL server and am working on creating tables i was given the following ERD and Constraints i'm not sure if my code matches the table in the erd any advice would be appreciated

Table 

Customer

CustomeNumber    Int  (PK)  
LastName         VarChar (30)  
FirstName        VarChar (30)  
Address(o)       VarChar (40)  
City(o)          VarChar (30)  
Province(o)      Char(2)  
PostalCode(o)    Char(6)  
HomePhone(o)     Char(10)  

Constraints  
Table----------Column -------Check------------Default    
Customer-----PostalCode-------L0L0L0     
Customer-----Province--------------------------------AB

I've got the following for my create table

    CREATE TABLE Customer
    (
        CustomerNumber int Constraint PK_Customer_CustomerNumber Primary Key Clustered,
        FirstName   varchar(30)         Constraint Customer_FirstName       not null,
        LastName    varchar(30)         Constraint Customer_LastName        not null,
        Address     varchar(40)         Constraint Customer_Address         not null,
        City        varchar(30)         Constraint Customer_City            not null,
        Province    char(2)             Constraint Customer_Province        not null,
        PostalCode  char(6)             Constraint Customer_PostalCode      not null,
        HomePhone   char(10)            Constraint Customer_HomePhone       not null,
    )

Solution

  • Try this... for your basic CREATE TABLE statement

    CREATE TABLE Customer
    (
    CustomerNumber int      NOT NULL  Primary Key Clustered,
    FirstName   varchar(30) not null,
    LastName    varchar(30) not null,
    Address     varchar(40) not null,
    City        varchar(30) not null,
    Province    char(2)     not null,
    PostalCode  char(6)     not null,
    HomePhone   char(10)    not null,
    )
    GO
    

    Read here to learn more about Default Constraints and Check Constraints