SQL Server builds tables and primary foreign KEY constraints with SQL commands

Source: Internet
Author: User

Establish dept and EMP Tables, and set the foreign keys of the EMP table with the dept_id in the Dept table

CREATE TABLE Dept (dept_name nvarchar () not NULL,    dept_address nchar (+), dept_id int constraint pk_dept primary key< C1/>--dept table's primary key, named pk_dept) CREATE TABLE emp (emp_name nvarchar) not null,emp_sex nchar (1), emp_age int,emp_id int Constraint Pk_emp primary key,     --emp table primary key dept_id int constraint fk_emp_dept foreign key references dept (dept_id)   --foreign key)

Insert and Constrain:

CREATE TABLE student (stu_id int constraint pk_stu primary key,stu_name nvarchar () unique NOT NULL,                --unique constraint, stu_n The value of AME cannot be repeated stu_sex nvarchar (1) NOT null default (' Male '),           --stu_sex is: male stu_sal int Check (stu_sal>=1000 and Stu_sal <=8000)   --check constraints, stu_sal values can only be between 1000 and 8000) insert into student (Stu_id,stu_name,stu_sal) VALUES (1, ' Zhang San ', 6000) ;    --no assignment to Stu_sex, the default is male insert into student values (2, ' John Doe ', ' Male ', 7000); INSERT into student values (3, ' Xiao Juan ', ' female ', 5000);

Results obtained:

SQL Server builds tables and primary foreign KEY constraints with SQL commands

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.