您的位置:首页 > 数据库

[SQL]SQL Server数据表的基础知识与增查删改

2014-03-22 21:44 507 查看
SQL Server数据表的基础知识与增查删改
由张晨辉(学生) 于19天 前发表 | 阅读94次
一、常用数据类型

1、整型:bigint、int、smallint、tinyint
2、小数:decimal、numeric
3、近似数字数据:float、real
4、货币数据:money、smallmoney
5、日期和时间:datetime、smalldatetime
6、字符数据:char、varchar、text
7、Unicode字符数据:nchar、nvarchar、ntext
8、二进制数据:binary、varbinary、ntext
9、其他:timestamp等
10、自定义用户类型的创建与删除:sp_addtype {type_name},[base_type] [,[‘NULL’|‘NOT NULL’]] [,’拥有者’]
Sp_droptype type_name
二、选择数据类型的指导原则
1、若列的值的长度相差很大,使用变长数据类型
2、谨慎使用tinyint数据类型
3、对于小数数据来说,多使用decimal数据类型
4、若行的存储量超过8000字节,使用text或者image
5、若不大于8 000字节,可使用char、varchar或者binary数据类型
6、货币数据,使用 money 数据类型
7、不要使用类型为 float 或者 real 的列作为主键
三、临时表
1、--创建全局临时表
CREATE TABLE ##GlobalTable
(
cola INT
)
2、--创建局部临时表
CREATE TABLE #LocationTable
(
cola INT
)

四、表
1、创建表
create table sales
(
order_no int not null,
order_date datetime not null,
ship_date datetime not null
)
2、修改表
exec sp_rename sales,ssaless
3、删除表
drop table sales
4、创建计算列的表
CREATE TABLE Sells
(
price money,
number int,
amount as price*number
)
5、创建函数列的表
CREATE TABLE TestTable
(
indate as getdate(),
id int,
usename AS USER_NAME()
)
6、修改表employee
ALTER TABLE employee
ADD  telephone int null,  --添加列:电话号码 telephone_no,添加列:字符列email为char
email char(29) null

ALTER TABLE employee  --修改列类型:email为varchar
ALTER COLUMN email varchar(20) null

ALTER TABLE employee   --修改列空为非空列
ALTER COLUMN email varchar(20) not null

Exec sp_rename ‘架构名.表名.旧字段名 ‘,新字段名,’column’  --修改字段名

ALTER TABLE employee  --删除列
DROP COLUMN email

五、约束:约束是一种限制。在列或表的层次设置约束,确保数据符合某种数据完整性规则。
1、主键约束
(1)在创建表时加主键约束
create table customers
(
CustomerNo int identity not null primary key,
CustomerName varchar(30)  not null
)
(2)在现有表中添加主键
alter table customers
add constraint PK_CustomerNo
Primary key (CustomerNo)
2、外键约束
(1)create table orders
(
OrderID int identity not null primary key,
CustomerNo int not null  Foreign key references CUSTOMERS(customerno)
)
(2)在已存在的表中添加外键
alter table orders
add constraint FK_EmployeeCreatesOrder
Foreign key (customerno) references customers(customerno)
3、唯一约束:列上有一个唯一的值。
(1)创建表时创建唯一约束
create table shippers
(
shipperid int identity not null
primary key ,
phoneno varchar(14) not null unique
)
(2)在已存在的表中创建唯一约束
alter table shippers
add constraint AK_ShippersPhoneNo
Unique(phoneno)
4、Check约束:Check约束比较好的方面是不限制于一个特定的列。Check约束使用与where子句一样的规则定义。
(1)添加Check约束
alter table customers
Add constraint cn_customerdateinsystem
Check
(DateInSystem<=GetDate())
(2)删除Check约束
alter table testtable
drop constraint cn_customerdateinsystem
5、Default
(1)创建默认值
create table shippers
(
shipperid int identity not null primary key,
dateinsystem smalldatetime not null default GetDate()
)
(2)在已存在的表上加默认值
Alter table customers
Add constraint cn_customerdefaultdateinsystem
Default getdate() for dateinsystem
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: