1. 程式人生 > >SQL Server語句建立資料庫和表——並設定主外來鍵關係

SQL Server語句建立資料庫和表——並設定主外來鍵關係

簡單的建立資料庫的 SQL 語句:

複製程式碼
 1 use master
 2 go
 3 
 4 if exists(select * from sysdatabases where name='Test')
 5 begin
 6     select '該資料庫已存在'
 7     drop database Test        --如果該資料庫已經存在,那麼就刪除它
 8 end
 9 else
10 begin
11     create database Test
12     on  primary        --表示屬於 primary 檔案組
13     (
14         name='stuDB_data',        -- 主資料檔案的邏輯名稱
15         filename='D:\stuDB_data.mdf',    -- 主資料檔案的物理名稱
16         size=5mb,    --主資料檔案的初始大小
17         maxsize=100mb,     -- 主資料檔案增長的最大值
18         filegrowth=15%        --主資料檔案的增長率
19     )
20     log on
21     (
22         name='stuDB_log',        -- 日誌檔案的邏輯名稱
23         filename='D:\stuDB_log.ldf',    -- 日誌檔案的物理名稱
24         size=2mb,            --日誌檔案的初始大小
25         maxsize=20mb,        --日誌檔案增長的最大值
26         filegrowth=1mb        --日誌檔案的增長率
27     )
28 end
複製程式碼

接下來是建立資料表的 SQL 語句:

1 use Test    --表示設定為在該資料庫(Test)執行下面的SQL語句
2 go

可以先執行一下以上語句。

或者在這裡選擇資料庫。

複製程式碼
 1 use Test    --表示設定為在該資料庫(Test)執行下面的SQL語句
 2 go
 3 
 4 if exists(select * from sysobjects where name='Student')
 5 begin
 6     select '該表已經存在'
 7     drop table Student        --刪除表
 8 end
 9 else
10 begin
11     create table Student
12     (
13         S_Id        int        not null    identity(1,1)    primary key,    --設定為主鍵和自增長列,起始值為1,每次自增1
14         S_StuNo        varchar(50)        not null,
15         S_Name        varchar(20)        not null,
16         S_Sex        varchar(10)        not null,
17         S_Height    varchar(10)        null,
18         S_BirthDate        varchar(30)        null
19     )
20 end
21 
22 --新增約束                        
23 alter table Student add constraint 
24 UQ_S_StuNo    --約束名
25 unique        --約束型別(唯一約束)
26 (S_StuNo)    --列名
27 
28 --刪除約束
29 alter table Student drop constraint
30 UQ_S_StuNo    --約束名
複製程式碼

SQL語句建立表變數:

複製程式碼
 1 declare @Score table
 2 (
 3     Id        int        not null,
 4     Name    varchar(50)  null
 5 ) 
 6 
 7 insert into @Score
 8 select '1','劉邦' union
 9 select '2','項羽'
10 
11 select * from @Score
複製程式碼

SQL語句建立臨時表:

複製程式碼
 1 -- ## 表示全域性臨時表
 2 create table ##temp
 3 (
 4     Id        int        not null,
 5     Name    varchar(10)        null
 6 )
 7 
 8 -- # 表示區域性臨時表
 9 create table #temp
10 (
11     Id        int        not null,
12     Name    varchar(10)        null
13 )
複製程式碼

SQL 語句建立表並設定主外來鍵關係:

複製程式碼
 1 if exists(select * from sysObjects where name='Course')
 2 begin
 3     select '該表已經存在'
 4     drop table Course
 5 end
 6 else
 7 begin
 8     create table Course
 9     (
10       --列名    欄位型別  是否為空   標識外來鍵列(外來鍵列名)         關聯表的表名(關聯的欄位名)
11          Stu_Id        int        null    foreign key(Stu_Id) references Student(S_Id),
12          C_Id        int        not null    identity(1,1)    Primary key,
13          C_Name        varchar(100)    not null
14      )
15 end
複製程式碼

注意:表變數和臨時表都不能新增約束,具體的特徵和適用場景請參見:

http://www.cnblogs.com/kissdodog/archive/2013/07/03/3169470.html