SqlServer基本常学语法(索性,触发器等都有)

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

S2_Sql 端口1433

第1章

1、创建一个数据文件和一个日志文件.

create database StuDB--数据裤名称

on primary--primary指定是主数据裤文件

(

name='StuDB_data',--name为数据文件的逻辑称

filename='f:\冯建\StuDB_data.mdf',--数据文件的物理名称

size=3mb,--数据文件的初始大小

maxsize=100mb,--数据文件增长的最大值

filegrowth=10%--数据文件的增长率

)

log on--日志文件,各参数含义同上

(

name='stuDB_log',

filename='f:\冯建\StuDB_log.ldf',

size=2mb,

filegrowth=1mb

)

2、删除数据裤..drop database 数据裤名

Sql Server 将数据裤的清单存放在master系统数据裤的sysdatabases表中,只需要查看该表中是否存于该数据库中就可以了。

use master--设置当前的数据库为master,以便访问sysdatabases表

go

if exists(select*from sysdatabases where name='stuDB')

drop database stuDB

create database stuDB

on

(

)

log on

(

)

Exists(查询语句)检测某个查询是否存在。如果查询语句返回的记录结果不为空,则表示存在;否则表示不存在。

3、创建学员信息表和删除学员信息表

--创建学员信息表

/*语法carate table 表名

(

字段 1数据类型列的特征

字段2 数据类型列的特征

....

)*/

use stuDB

go

if exists(select*from sysobjects where type='u'and name=StuInfo) drop table StuInfo –-删除表的语句

create table StuInfo

(

stuname varchar(20)not null,--学员姓名,非空

stuNo char(6)not null,--学号,非空

StuID numeric(18,0), --身份证号码,numeric(18,0)代表位数字,小数位数为位stuSeat smallint identity(1,1),--座位号,自动编号(标识列),identity(起始值,递增量)

stuAddress text--允许为,住址

)

4、使用sql语句创建和删除约束

添加约束语法:

Alter table 表名

Add constraint 约束名约束类型具体的约束说明

删除约束语法:

alter table stuInfo

drop constraint 约束名

--添加主键约束将stuNO作为主键

alter table stuInfo

add constraint PK_stuNo primary key(stuNo)

--添加唯一约束(身份证号唯一,建立唯一约束)

alter table stuInfo

add constraint UQ_StuID unique(stuID)

--添加默认约束(地址默认为“地址不详”)

alter table stuInfo

add constraint DF_stuAddress default('地址不详')for stuAddress

--添加检查约束(年龄)

alter table stuInfo

add constraint CK_stuAge check(Stuage between 15 and 40)

--添加外键约束(主表stuInfo和从表StuMarks建立关系,关系字段为stuNO)

alter table stuMarks

add constraint FK_stuNO foreign key(stuNO) references stuInfo(stuNO)

5.使用SQL语句创建登录

1、创建windows登录账户语法:exec sp_grantlogin‘windows域名\域账户’

2、创建sql登录账户语法:exec sp_addlogin‘账户名’,’密码’

3、创建数据库用户:需调用系统存储过程sp_grantdbaccess

exec sp_grantdbaccess ‘登录账户’,’数据库用户’

4、给数据库用户授权:常用的权限包括insert,delete,update,select,create table等等

语法:grant权限[on 表名] to 数据库用户

6、视图和索引

---创建索引的语法

if exists(select*from sysindexes where name='index_name')

create [unique] [clustered] [nonclustered]index index_name on table_name(指定的字段)

[with

fillfactor=X]

--指定按索引查询

select*from table_name with(index_name)

where [......]

--创建视图的语法

create view view_name

as

7、触发器

1、语法: if exists(select * from sysobjects where name='trigger_name')

drop trigger trigger_name

go

create trigger trigger_name

on table_name

[with encryption]

for [delete,insert,update]

as

T-SQL语句

Go

2、instead of 触发器

---以下删除使用instead of触发器实现,原因:after触发器不能删除有主外键关系表的数据create trigger cardInfoDelete

on cardInfo

instead of delete

as

set nocount on

begin

declare @cardid char(19)

select @cardid=cardid from deleted

相关文档
最新文档