27、SQL Server 数据架构创建之数据列的创建

数据列的创建

一、数据类型

1、字符型

char(n)

nchar(n)

varchar(n) varchar(max)

nvarchar(n)  --unicode编码 当有多国语言时,可选择使用。

nvarchar(max)

text

ntext

sysname

2、数字数据类型

bit

tinyint

smallint

int

bigint

decimal  | numeric

money

smallmoney

float

real

3、日期/时间

datetime

smalldatetime

4、其他数据类型

timestamp  随机值

uniqueidentifiler

binary(n)

binary(max)

varbinary(n)

varbinary(max)

image

sql_variant

二、计算列(表达式列)

如:

create table a

(

s1 int,

s2 int,

s3 as s1+s2

)


三、更约束和默认值

1、主键约束 2、外键约束 3、为空性 4、Check约束 5、唯一约束 6、列默认值

注:如同前面介绍创建主键和外键的方法

not null、check()、unique、default()

1、列的为空性

null 

not null

如:

create table a

(

s1 int null,

s2 int not null

)


 

2、唯一约束

在创建表时在列后加unique

或者

使用alter table add constraint添加

如:

create table Student

(

id int not null,

name varchar(20),

address varchar(20) unique

)


创建表后(前提是没有添加约束)

 

alter table Student add constraint Student_UQ_address unique(address)


 

3、Check约束

同上有两个方法:

如:

create table Student

(

id int not null,

name varchar(20),

address varchar(20),

sex char(2) check(sex in('男','女'))

)


 

alter table Student add constraint Stu_CHECK_sex check(sex in('男','女'))


 

4、默认值选项

同上有两种方法

1、default 值

2、default 值 for 列名

注:在创建表时,可以将所有的约束全部定义在表定义时的最后。如:

create table Student

(

id int,

name varchar(20),

address varchar(20),

sex char(2),

constraint Stu_Check_SEX check(sex in('男','女')),

constraint Stu_PK_id primary key (id),

)


 

posted @ 2013-06-15 15:31  jlins  阅读(365)  评论(0编辑  收藏  举报