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

SQL Server数据表的基础知识与增查删改
由张晨辉(学生) 于19天 前发表 | 阅读94次
一、常用数据类型 、整型:bigint、int、smallint、tinyint
、小数:decimal、numeric
、近似数字数据:float、real
、货币数据:money、smallmoney
、日期和时间:datetime、smalldatetime
、字符数据:char、varchar、text
、Unicode字符数据:nchar、nvarchar、ntext
、二进制数据:binary、varbinary、ntext
、其他:timestamp等
、自定义用户类型的创建与删除:sp_addtype {type_name},[base_type] [,[‘NULL’|‘NOT NULL’]] [,’拥有者’]
Sp_droptype type_name
二、选择数据类型的指导原则
、若列的值的长度相差很大,使用变长数据类型
、谨慎使用tinyint数据类型
、对于小数数据来说,多使用decimal数据类型
、若行的存储量超过8000字节,使用text或者image
、若不大于8 000字节,可使用char、varchar或者binary数据类型
、货币数据,使用 money 数据类型
、不要使用类型为 float 或者 real 的列作为主键
三、临时表
、--创建全局临时表
CREATE TABLE ##GlobalTable
(
cola INT
)
、--创建局部临时表
CREATE TABLE #LocationTable
(
cola INT
) 四、表
、创建表
create table sales
(
order_no int not null,
order_date datetime not null,
ship_date datetime not null
)
、修改表
exec sp_rename sales,ssaless
、删除表
drop table sales
、创建计算列的表
CREATE TABLE Sells
(
price money,
number int,
amount as price*number
)
、创建函数列的表
CREATE TABLE TestTable
(
indate as getdate(),
id int,
usename AS USER_NAME()
)
、修改表employee
ALTER TABLE employee
ADD telephone int null, --添加列:电话号码 telephone_no,添加列:字符列email为char
email char() null ALTER TABLE employee --修改列类型:email为varchar
ALTER COLUMN email varchar() null ALTER TABLE employee --修改列空为非空列
ALTER COLUMN email varchar() not null Exec sp_rename ‘架构名.表名.旧字段名 ‘,新字段名,’column’ --修改字段名 ALTER TABLE employee --删除列
DROP COLUMN email 五、约束:约束是一种限制。在列或表的层次设置约束,确保数据符合某种数据完整性规则。
、主键约束
()在创建表时加主键约束
create table customers
(
CustomerNo int identity not null primary key,
CustomerName varchar() not null
)
()在现有表中添加主键
alter table customers
add constraint PK_CustomerNo
Primary key (CustomerNo)
、外键约束
()create table orders
(
OrderID int identity not null primary key,
CustomerNo int not null Foreign key references CUSTOMERS(customerno)
)
()在已存在的表中添加外键
alter table orders
add constraint FK_EmployeeCreatesOrder
Foreign key (customerno) references customers(customerno)
、唯一约束:列上有一个唯一的值。
()创建表时创建唯一约束
create table shippers
(
shipperid int identity not null
primary key ,
phoneno varchar() not null unique
)
()在已存在的表中创建唯一约束
alter table shippers
add constraint AK_ShippersPhoneNo
Unique(phoneno)
、Check约束:Check约束比较好的方面是不限制于一个特定的列。Check约束使用与where子句一样的规则定义。
()添加Check约束
alter table customers
Add constraint cn_customerdateinsystem
Check
(DateInSystem<=GetDate())
()删除Check约束
alter table testtable
drop constraint cn_customerdateinsystem
、Default
()创建默认值
create table shippers
(
shipperid int identity not null primary key,
dateinsystem smalldatetime not null default GetDate()
)
()在已存在的表上加默认值
Alter table customers
Add constraint cn_customerdefaultdateinsystem
Default getdate() for dateinsystem
上一篇:SQL Server 复制 - 发布订阅(SQL Server 数据同步)


下一篇:实验五 TCP传输及加解密