SQLServer sp_help使用方法

       给大家介绍一个在SQLServer中非常实用的一个存储过程,在SQL Server中,sp_help 存储过程用于显示有关数据库对象(如表、视图或存储过程)的信息。它提供有关指定对象的结构和属性的详细信息。使用 sp_help 的语法如下:

sp_help [ [ @objname = ] 'name' ]
  • @objname:要检索信息的数据库对象的名称。这是一个可选参数。

如果提供了 @objname 参数,sp_help 将显示有关指定对象的信息。如果省略该参数,sp_help 将显示当前数据库中对象的列表。

       查看表的信息:

EXEC sp_help 'a';    --查看表的信息

       查看存储过程的信息: 

EXEC sp_help 'Pro_test';	--查看存储过程

 

       其他的像视图、数据库的信息等都可以查看。 

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
---创建数据库 create database CRM; --删除数据库 drop database CRM; --创建一个表 if exists(select * from sysobjects where name='Users') drop table Users go create table Users( Id int identity(1,1) not null primary key, --顾客编号,主键 按一进行自动增长 UserName varchar(50)not null, PassWord varchar(50)not null, Address varchar(250)not null, ) go ----------------------------------------插入100条数据进Users表,进行下面对分页做准备---------------- Begin Declare @n bigint Declare @Sql nvarchar(225) set @n=0 While @n<100--导入100条相同的数据进Users表 Begin Set @Sql='Insert into Users Values(''jilongliang'',''123456'',''广东阳春'')' Exec (@Sql) set @n=@n+1 End End ------------查询一下是不是插入--------------- Select *from Users; -------------------------存储过程创建语法----------------------------------- /* 1.存储过程创建语法 create proc | procedure pro_name [{@参数数据类型} [=默认值] [output], {@参数数据类型} [=默认值] [output], .... ] as SQL_statements */ --------------------------------------------------------------------------------- -------------------------- 带参存储过程----------------------------------- if (object_id('proc_find_users', 'P') is not null) drop proc proc_find_users go create proc proc_find_users(@startId int, @endId int) as ---between and 表示在那个两个数字之间 select * from users where Id between @startId and @endId go exec proc_find_users 42, 64; --------------------------------------------------------------------------------- --------------------------------带通配符参数存储过程----------------------------- if (object_id('proc_findUsersByName', 'P') is not null) drop proc proc_findUsersByName go create proc proc_findUsersByName(@UserName varchar(20) = '%j%', @nextName varchar(20) = '%') as select * from Users where UserName like @UserName and UserName like @nextName; go exec proc_findUsersByName; exec proc_findUsersByName '%l%', 'j%'; --------------------------------------------------------------------------------------- ----------------------------------------带输出参数存储过程--------------------------------------- if (object_id('proc_getUsersRecord', 'P') is not null) drop proc proc_getUsersRecord go create proc proc_getUsersRecord( @Id int, --默认输入参数 @UserName varchar(20) out, --输出参数 @address varchar(20) output --输入输出参数 ) as select @UserName = UserName, @address = address from Users where Id = @Id and Address = @address; go ---------------声明变量 declare @id int, @address varchar(20), @UserName varchar(20), @temp varchar(20); set @id = 71; set @temp = 1; exec proc_getUsersRecord @id, @UserName out, @temp output; select @UserName as 用户名, @temp as temp,@address as 地址; print @UserName + '#' + @temp; --------------------------------------------------------------------------------------- -----------------------------------不缓存存储过程--------------------------------------- --WITH RECOMPILE 不缓存 if (object_id('proc_temp', 'P') is not null) drop proc proc_temp go create proc proc_temp with recompile as select * from users; go exec proc_temp; -----------------------------------加密存储过程------------------------------------- --加密WITH ENCRYPTION if (object_id('proc_temp_encryption', 'P') is not null) drop proc proc_temp_encryption go create proc proc_temp_encryption with encryption as select * from users; go exec proc_temp_encryption; exec sp_helptext 'proc_temp'; exec sp_helptext 'proc_temp_encryption'; -----------------------------------带游标参数存储过程------------------------------------- if (object_id('proc_cursor', 'P') is not null) drop proc proc_cursor go create proc proc_cursor @cur cursor varying output as set @cur = cursor forward_only static for select Id, UserName, Address from Users; open @cur; go --调用 declare @exec_cur cursor; declare @Id int, @UserName varchar(50), @Address varchar(250); exec proc_cursor @cur = @exec_cur output;--调用存储过程 fetch next from @exec_cur into @Id, @UserName, @Address; while (@@fetch_status = 0) begin fetch next from @exec_cur into @Id, @UserName, @Address; print 'Id: ' + convert(varchar, @Id) + ', name: ' + @UserName + ', Address: ' + @Address; end close @exec_cur; deallocate @exec_cur;--删除游标 ---------------------------------------------------------- select * from sys.messages; --使用sysmessages定义的消息 --------------------------------Query--------------------- Create PROCEDURE proc_LoginUser @userName varchar(50), @password varchar(50) as begin select UserName,PassWord from Users where UserName = @userName and PassWord = @PassWord end GO --这个Go注意不要放在Exec后面,否则报超出了存储过程、函数、 --触发器或视图的最大嵌套层数(最大层数为 32) exec proc_LoginUser @userName = 'admin',@PassWord = 'admin' --------------------------------Insert--------------------- Create proc proc_InsertUsers @UserName varchar(50), @PassWord varchar(50), @Address varchar(150) as insert into proc_InsertUsers values(@UserName,@PassWord,@Address) --------------------------------Update--------------------- --修改模块信息,根据模块Id Create proc proc_UpdateUser @UserName varchar(50), @PassWord varchar(50), @Address varchar(150), @Id int as update Users set UserName=@UserName,PassWord=@PassWord ,Address=@Address where Id = @Id --------------------------------Delete--------------------- Create proc proc_DeleteById @Id int as delete from Users where Id=@Id ----------------------------------------------------------- ------------------------------------------------------------------------------------- ----------------------------------分页存储过程-------------------------------------- ------------------------------------------------------------------------------------- If (object_id('pro_page', 'P') is not null) drop proc proc_Page GO create procedure proc_Page( @pageIndex int, @pageSize int ) as declare @startRow int, @endRow int --声明变量 set @startRow = (@pageIndex - 1) * @pageSize +1 --设值 set @endRow = @startRow + @pageSize -1 --设值 select ID,UserName,Address,PassWord,t.number from --t.number的行号 ( select ID,UserName,Address,PassWord, row_number() over (order by id asc) as number from Users ) t where t.number between @startRow and @endRow; GO ----执行 exec proc_Page 1, 3; -- 一页,三条数据 ------------------------------------------------------------------------------------- ---存储过程、row_number完成分页 if (object_id('pro_page', 'P') is not null) drop proc proc_cursor -- drop proc pro_page go create proc pro_Page @startIndex int, @endIndex int as select count(*) as Total from Users; --计算出来总数 select * from ( select row_number() over(order by Id) as rowId, * from Users ) temp where temp.rowId between @startIndex and @endIndex go exec pro_Page 1, 4 ------------------------------------------------------------------------------------- -------------------------------------数据库函数-------------------------------------- exec sp_databases; --查看数据库 exec sp_tables; --查看表 exec sp_columns users;--查看列 exec sp_helpIndex users;--查看索引 exec sp_helpConstraint users;--约束 exec sp_stored_procedures; exec sp_helptext 'sp_stored_procedures';--查看存储过程创建、定义语句 exec sp_rename users, stuInfo;--修改表、索引、列的名称 exec sp_renamedb myTempDB, myDB;--更改数据库名称 exec sp_defaultdb 'master', 'myDB';--更改登录名的默认数据库 exec sp_helpdb;--数据库帮助,查询数据库信息 exec sp_helpdb master; ------------------------------------------------------------------------------------- ---------------------------数据库sp_rename重命名函数------------------------------- --表重命名 exec sp_rename 'users', 'tb_users'; select * from tb_users; --列重命名 exec sp_rename 'tb_users.name', 'sName', 'column'; exec sp_help 'tb_users'; --重命名索引 exec sp_rename N'tb_users.idx_cid', N'idx_cidd', N'index'; exec sp_help 'tb_users'; --查询所有存储过程 select * from sys.objects where type = 'P'; select * from sys.objects where type_desc like '%pro%' and name like 'sp%';
以SQL Server为工具,讲解SQL语言的应用,提供了近500个曲型应用,读者可以随查随用,深入讲解SQL语言的各种查询语句,详细介绍数据库设计及管理,详细讲解存储过程、解发器和游标等知识,讲解了SQL语言在高级语言的具体应用。 第1章 SQL语言的概述 1.1 认识SQL语言 1.1.1 什么是SQL语言 1.1.2 SQL的历史与发展 1.1.3 SQL的功能和优点 1.2 认识数据库 1.2.1 什么是数据库 1.2.2 数据库系统的结构 1.2.3 数据库系统的工作流程 1.2.4 常见的SQL数据库管理系统 1.3 数据模型 1.3.1 关系数据库模型 1.3.2 数据模型的构成 1.3.3 常见的数据模型 1.4 关系型数据库 1.4.1 关系型数据库的定义 1.4.2 关系型数据库与表 1.4.3 主键与外键 1.4.4 字段约束 1.4.5 数据的完整性 1.4.6 关系数据库设计原则 1.5 SQL开发环境 1.5.1 SQL环境介绍 1.5.2 SQL的层次结构 1.5.3 SQL环境的对象 1.5.4 SQL环境的程序系统 1.6 SQL语句基础 1.6.1 SQL常量 1.6.2 SQL表达式 1.6.3 SQL数据类型 1.6.4 注释符 1.6.5 批处理 1.6.6 SQL语句的执行 1.7 SQL语法知识 1.7.1 SQL语法结构 1.7.2 常用的SQL语句 1.8 小结第2章 设计数据库 2.1 设计数据库基础 2.1.1 数据库设计定义 2.1.2 设计数据库的意义 2.1.3 进行数据库设计的方法 2.2 数据实体和联系 2.2.1 实体、属性与联系 2.2.2 一对一联系 2.2.3 一对多联系 2.2.4 多对多联系 2.3 规范化准则 2.3.1 范式 2.3.2 第一范式 2.3.3 第二范式 2.3.4 第三范式 2.3.5 第四范式 2.4.小结第2篇 数据库管理篇第3章 数据库的相关操作 3.1 创建数据库 3.1.1 SQL标准创建数据库的语法 3.1.2 使用SQL语句创建数据库 3.2 删除数据库 3.2.1 SQL标准删除数据库的语法 3.2.2 使用SQL语句删除数据库 3.3 修改数据库 3.3.1 修改数据库语法 3.3.2 使用SQL语句修改数据库 3.4 管理数据库 3.4.1 扩充与压缩数据库 3.4.2 导入与导出数据 3.4.3 数据库的备份与恢复 3.4.4 使用sp_helpdb查看数据库信息 3.5 小结第4章 数据表的相关操作 4.1 SQL的数据表 4.1.1 数据表的结构 4.1.2 数据表的种类 4.2 创建数据表 4.2.1 创建数据表的语句结构 4.2.2 创建基本表 4.2.3 非空约束 4.2.4 DEFAULT指定缺省值 4.3 修改数据表 4.3.1 修改数据表的语句结构 4.3.2 给数据表增添新列 4.3.3 修改数据表的列 4.3.4 删除数据表的列 4.4 数据表的删除 4.4.1 删除数据表的语句结构 4.4.2 使用SQL语句删除数据表 4.5 数据表的重命名 4.5.1 重命名数据表的语句 4.5.2 使用SQL语句重命名数据表 4.6 小结第5章 索引与视图 5.1 索引的基础知识 5.1.1 索引的概念 5.1.2 索引的类型 5.1.3 索引的结构 5.2 创建索引 5.2.1 创建索引的语句结构 20.3.3 子查询的实现 20.3.4 复合查询的实现 20.4 运算符与表达式的应用 20.4.1 连接数据表的实现 20.4.2 算术运算符的应用 20.4.3 表达式的应用 20.5 数据维护与触发器的应用 20.5.1 添加数据的实现 20.5.2 更新数据的实现 20.5.3 删除数据的实现 20.5.4 在VB.NET应用触发器20.6 小结第21章 VB 6.0与SQL Server的开发与应用 21.1 VB 6.0开发环境 21.1.1 VB 6.0介绍 21.1.2 VB 6.0的版本 21.1.3 VB 6.0开发环境 21.2 VB 6.0连接数据库 21.2.1 VB 6.0数据库控件介绍 21.2.2 数据库连接举例 21.3 数据查询应用 21.3.1 普通数据查询的实现 21.3.2 连接查询的实现 21.3.3 子查询的实现 21.3.4 复合查询的实现 21.4 运算符与表达式的应用 21.4.1 连接数据表的实现 21.4.2 算术运算符的应用 21.4.3 表达式的应用 21.5 数据维护操作的应用 21.5.1 添加数据的实现 21.5.2 更新数据的实现 21.5.3 删除数据的实现 21.6 触发器与存储过程的应用 21.6.1在VB 6.0应用触发器 21.6.2在VB 6.0应用存储过程 21.7 小结第22章 VC++6.0与SQL Server的开发与应用 22.1 VC++6.0开发环境 22.1.1 VC++6.0介绍 22.1.2 MFC编程 22.1.3 VC++6.0开发环境 22.2 VC++6.0连接数据库 22.2.1 ADO数据控件介绍 22.2.2 数据库连接举例 22.3 数据查询应用 22.3.1 普通数据查询的实现 22.3.2 连接查询的实现 22.3.3 子查询的实现 22.3.4 复合查询的实现 22.4 运算符与表达式的应用 22.4.1 连接数据表的实现 22.4.2 算术运算符的应用 22.4.3 表达式的应用 22.5 数据维护操作的应用 22.5.1 添加数据的实现 22.5.2 更新数据的实现 22.5.3 删除数据的实现 22.6 小结第23章 PHP访问 SQL Server 2005 23.1 PHP开发环境 23.1.1 PHP简介及其特点 23.1.2 PHP开发环境的安装 23.2 PHP连接SQL Server服务器 23.2.1 使用PHP的MSSQL扩展 23.2.2 PHP连接SQL Setver的必要条件 23.3 使用PHP存取SQL Server数据库 23.3.1 选择操作的数据库 23.3.2 在数据库创建表 23.3.3 删除存在的数据表 23.4 对数据库表的操作 23.4.1 向表添加记录 23.4.2 浏览表记录 23.4.3 修改已有记录 23.4.4 删除指定记录 23.5 可回复留言板的开发(PHP+SQL Server) 23.5.1 数据表的设计 23.5.2 配置文件的创建 23.5.3 创建系统运行的表 23.5.4 创建留言显示模块 23.5.5 创建留言添加模块 23.5.6 进入留言管理模块 23.5.7 创建留言修改模块 23.5.8 创建留言删除模块 23.6 小结 5.2.2 创建非簇索引 5.2.3 创建簇索引 5.2.4 创建惟一索引 5.2.5 创建复合索引 5.3 删除索引 5.3.1 删除索引的语句结构 5.3.2 使用SQL语句删除索引 5.4 视图的基础知识 5.4.1 视图概述 5.4.2 视图的优点与缺点 5.5 视图的基本操作 5.5.1 创建视图的基本语句结构 5.5.2 使用SQL语句创建视图 5.5.3 修改视图的语句结构 5.5.4 重命名视图的名称 5.5.5 使用SQL语句修改视图 5.5.6 删除视图的语句结构 5.5.7 使用SQL语句删除视图 5.6 视图的应用 5.6.1 利用视图简化表的复杂连接 5.6.2 利用视图简化复杂查询 5.7 小结第3篇 SQL查询篇第6章 简单的SELECT语句查询 6.1 查询的基本结构 6.1.1 了解SELECT语句 6.1.2 SELECT语句的语法格式 6.1.3 SELECT语句的执行步骤 6.2 简单的查询语句 6.2.1 查询表指定的字段 6.2.2 查询所有的字段 6.2.3 使用DISTINCT去除重复信息 6.2.4 使用别名 6.3 排序与分组 6.3.1 升序排序与降序排序 6.3.2 多列字段排序 6.3.3 使用GROUPBY子句对查询结果进行分组 6.3.4 HAVING子句的应用 6.4 条件查询 6.4.1 WHERE单条件语句查询 6.4.2 运算符查询 6.4.3 BETWEEN运算符范围筛选 6.4.4 使用TOP子句 6.4.5 NULL的判断 6.5 模糊查询 6.5.1 使用LIKE运算符进行查询 6.5.2 使用“_”通配符进行查询 6.5.3 使用“%”通配符进行查询 6.5.4 使用“[]”通配符进行查询 6.5.5 使用“[^]”通配符进行查询 6.6 小结第7章 运算符与表达式相关查询 7.1 逻辑运算符 7.1.1 逻辑与运算符 7.1.2 逻辑或运算符 7.1.3 逻辑运算符的组合使用 7.2 IN运算符 7.2.1 IN运算符的使用 7.2.2 NOT IN运算符的使用 7.3 NOT运算符与BETWEEN运算符 7.3.1 N0T运算符的使用 7.3.2 NOT运算符与BETWEEN运算符的组合应用 7.4 数学运算符 7.4.1 数学运算符的种类 7.4.2 数学运算符的应用 7.5 集合查询运算符 7.5.1 UNION运算符 7.5.2 INTERSECT运算符 7.6运算符的组合应用 7.6.1 逻辑运算符与IN运算符的组合应用 7.6.2 逻辑运算符与NOT运算符的组合应用 7.6.3 逻辑运算符与数学运算符的组合应用 7.6.4 逻辑运算符与集合运算符的组合应用 7.6.5 数学运算符与NOT运算符的组合应用 7.6.6 数学运算符与IN运算符的组合应用 7.6.7 数学运算符与集合运算符的组合应用 7.7 SQL的表达式 7.7.1 CAST表达式的应用 7.7.2 CASE表达式的应用 7.8 小结第8章 SQL函数 8.1 SQL函数基础 8.1.1 SQL语句函数 8.1.2 常用的SQL语句函数 8.2 日期函数和数学运算函数 8.2.1 日期时间函数 8.2.2 CONVERT函数转换日期、时间 8.2.3 数据运算函数 8.3 字符串函数 8.3.1 字符串处理函数介绍 8.3.2 字符转换函数 8.3.3 去字符串空格函数 8.3.4 取字符串长度的函数 8.3.5 查询包含部分字符串内容的数据 8.3.6 颠倒字符串的顺序 8.3.7 字符串替换 8.4 聚合函数 8.4.1 聚合函数概述 8.4.2 SUM函数运算 8.4.3 MAX函数运算 8.4.4 MIN函数运算 8.4.5 AVG函数运算 8.4.6 COUNT函数运算 8.4.7 聚合函数的组合使用 8.5 小结第9章 连接查询 9.1 多表连接 9.1.1 多表连接的优点 9.1.2 简单的两表连接 9.1.3 多表连接举例 9.1.4 UNION JOIN连接表 9.2 自连接与自然连接 9.2.1 自连接 9.2.2 自然连接 9.3 内连接 9.3.1 等值连接 9.3.2 不等值连接 9.3.3 使用内连接实现多表连接 9.3.4 在内连接使用聚合函数 9.4 外连接 9.4.1 左外连接 9.4.2 右外连接 9.4.3 全外连接 9.4.4 在外连接使用聚合函数 9.5 交叉连接 9.5.l 交叉连接的定义 9.5.2 交叉连接举例 9.6 多表连接的综合应用 9.6.1 内连接与左外连接的综合应用 9.6.2 内连接与右外连接的综合应用 9.6.3 UNION集合运算与多表连接应用 9.7 小结第10章 子查询 10.1 子查询的简单应用 10.1.1 子查询概述 10.1.2 在多表查询使用子查询 10.1.3 在子查询使用聚合函数 10.1.4 使用ANY或ALL运算符 10.1.5 使用子查询创建视图 10.2 使用IN语句的子查询 10.2.1 简单的IN语句子查询 10.2.2 使用IN子查询实现集合交运算 lO.2.3 使用IN子查询实现集合差运算 10.3 使用EXISTS语句的子查询 10.3.1 简单的EXISTS语句子查询 10.3.2 使用EXISTS子查询实现两表交集 10.3.3 使用EXISTS子查询实现两表并集 10.3.4 使用NOT EXISTS的子查询 10.4 相关子查询 10.4.1 使用IN引入相关子查询 10.4.2 使用比较运算符引入相关子查询 10.4.3 在HAVING子句使用相关子查询 10.5 UNIQUE子查询与嵌套子查询 10.5.1 UNIQUE子查询 10.5.2 嵌套子查询 10.6 小结第4篇 T-SQL开发常用操作篇第11章 数据的维护操作 11.1 数据的插入操作 11.1.1 INSERT语句的基本语法 11.1.2 插入单条记录 11.1.3 NULL的插入 11.1.4 由VALUES关键字插入多行数据 11.1.5 使用SELECT语句插入数据 11.1.6 通过视图插入数据 11.1.7 使用子查询插入数据 11.2 数据的更新操作 11.2.1 UPDATE语句的基本语法 11.2.2 使用UPDATE语句更新指定的列值 11.2.3 数据字段NULL的更改 11.2.4 更新全部数据 11.2.5 利用子查询更新数据 11.2.6 通过视图更新表数据 11.3 数据的删除操作 11.3.1 DELETE语句的语法结构 11.3.2 删除指定行的数据 11.3.3 删除所有数据 11.3.4 通过视图删除表数据 11.3.5 使用子查询删除数据 11.3.6 使用TRUNCATE TABLE语句 11.4 小结第12章 完整性控制 12.1 完整性约束概述 12.1.1 数据的完整性简介 12.1.2 完整性约束的类型 12.1.3 数据完整性的意义 12.2 约束 12.2.1 DEFAULT约束 12.2.2 CHECK约束 12.2.3 PRIMARY KEY约束 12.2.4 UNIQUE约束 12.2.5 FOREIGN KEY约束 12.2.6 NOT NULL约束 12.2.7 列约束和表约束 12.3 规则 12.3.1 创建规则 12.3.2 规则的绑定与松绑 12.4 域约束与断言 12.4.1 域与域约束 12.4.2 利用断言创建多表约束 12.5 默认值 12.5.1 创建默认值 12.5.2 默认值的绑定与松绑 12.6 小结第5篇 T-SQL高级编程篇第13章 存储过程 13.1 存储过程概述 13.1.1 存储过程的基本概念 13.1.2 存储过程的优缺点 13.2 存储过程常用的流控制语句 13.2.1 IF...LSE语句 13.2.2 BEGIN...END语句 13.2.3 DECLARE语句 13.2.4 GOTO语句 13.2.5 WAITFOR语句 13.2.6 WHILE、BREAK和CONTINUE语句 13.2.7 PRINT语句 13.2.8 RETURN语句 13.2.9 注释 13.3 创建与执行存储过程 13.3.1 创建存储过程 13.3.2 创建带参数的存储过程 13.3.3 创建带0UTPUT返回,参数的存储过程 13.3.4 执行存储过程 13.4 存储过程的查看、修改和删除 13.4.1 系统存储过程 13.4.2 存储过程的查看 13.4.3 存储过程的重命名 13.4.4 修改存储过程 13.4.5 存储过程的删除 13.5 Oracle数据库的控制流语句 13.5.1 IF条件语句 13.5.2 LOOP循环语句 13.5.3 FOR循环语句 13.5.4 WHILE循环语句 13.5.5 GOTO语句 13.6 Oracle数据库的存储过程 13.6.1 0racle数据库创建存储过程 13.6.2 Oracle数据库存储过程的执行 13.7 小结第14章 触发器 14.1 触发器的基础知识 14.1.1 触发器的概念 14.1.2 触发器的种类 14.1.3 触发器的组成 14.1.4 触发器的优点 14.1.5 触发器执行环境 14.2 触发器的创建 14.2.1 创建触发器的语法结构 14.2.2 Inserted表和Deleted表 14.2.3 INSERT触发器 14.2.4 UPDATE触发器 14.2.5 DELETE触发器 14.2.6 INSTEAD OF触发器 14.2.7 嵌套触发器 14.2.8 递归触发器 14.3 查看触发器 14.3.1 使用系统存储过程sp_help查看触发器 14.3.2 使用系统存储过程sp_helptext查看触发器 14.3.3 使用系统存储过程sp_depengs查看触发器 14.4 触发器的修改及删除 14.4.1触发器的修改 14.4.2触发器的删除 14.5 Oracle数据库的触发器 14.5.1 Oracle触发器类型 14.5.2 触发器的创建 14.5.3 Oracle触发器的启用与禁用 14.5.4 0racle触发器的删除 14.6 小结第15章 游标 15.1 游标的定义 15.1.1 游标的基本概念 15.1.2 游标的分类 15.1.3 游标的作用及其应用 15.2 游标的使用 15.2.1 游标的创建 15.2.2 打开游标 15.2.3 关闭游标 15.2.4 释放游标 15.2.5 使用游标 15.2.6 检索游标 15.2.7 游标变量 15.3 游标的展使用 15.3.1 用于UJPDATE操作的可更新游标 15.3.2 用于DELETlE操作的可更新游标 15.3.3 可更新游标的综合操作 15.3.4 使用@@CURSOR_ROWS全局变量确定游标的行数 15.3.5 使用@@FETCh_STATJS全局变量检测FETCH操作的状态 15.3.6 使用系统过程管理游标 15.4 Oracle游标的使用 15.4.1 显式游标与隐式游标 15.4.2 游标属性 15.4.3 参数化游标 15.4.4 游标的循环 15.5 小结第16章 事务控制和锁定 16.1 事务 16.1.1 事务概述 16.1.2 事务的特性 16.1.3事务的分类 16.2 事务控制 16.2.1 事务控制操作 16.2.2 开始事务 16.2.3 提交事务 16.2.4 回滚事务 16.2.5 设置事务保存点 16.2.6 终止事务 16.3 并发控制 16.3.1 并发操作的问题 16.3.2 事务隔离级别 16.4 锁定 16.4.1 锁的作用及含义 16.4.2 锁的类型 16.4.3 SQL Server表级锁的使用 16.4.4 设置隔离级别实现并发控制 16.4.5 死锁及其处理 16.5 小结第17章 SQL安全 17.1 SQL安全概述 17.1.1 SQL安全的重要性 17.1.2 SQL安全的对象和权限 17.2 用户管理 17.2.1 创建SQL用户 17.2.2 删除SQL用户 17.3 角色管理 17.3.1 角色的优点 17.3.2 创建角色 17.3.3 删除角色 17.3.4 授予角色 17.3.5 取消角色 17.4 权限管理 17.4.1 授予权限 17.4.2 撤销权限 17.4.3 查询权限控制 17.4.4 插入操作权限控制 17.4.5 删除操作权限控制 17.4.6 更新操作权限控制 17.5 SQL Server的安全管理 17.5.1 SQL Server的用户管理 l7.5.2 SQL Server的角色管理 l7.5.3 SQL Server的权限管理 17.6 Oracle的安全管理 17.6.1 Oracle的用户管理 17.6.2 Oracle的权限管理 17.7小结第18章 嵌入式SQL 18.1 SQL的调用 18.1.1 直接调用SQL 18.1.2 SQL调用层接口(CLI) 18.2 嵌入式SQL的使用 18.2.1 嵌入式SQL 18.2.2 SQL通信区 18.2.3 主变量 18.2.4 在嵌入式SQL使用SQL语句 18.2.5 在嵌入式SQL使用游标 18.3 嵌入式SQL在SQL Server应用 18.3.1 嵌入式SQL代码 18.3.2 预编译文件 18.3.3 设置连接VC++6.O 18.3.4 编译运行程序 18.4 小结第6篇 T-SQL结合流行语言进行开发篇第19章 C#与SQL Server的开发与应用 19.1 C#开发环境 19.1.1 C#介绍 19.1.2 C#开发环境 19.2 C#连接数据库 19.2.1 C#数据库控件介绍 19.2.2 数据库连接举例 19.3 数据查询应用 19.3.1 普通数据查询的实现 19.3.2 连接查询的实现 19.3.3 子查询的实现 19.3.4 复合查询的实现 19.4 运算符与表达式的应用 19.4.1 连接数据表的实现 19.4.2 算术运算符的应用 19.4.3 表达式的应用 19.5 数据维护操作的应用 19.5.1 添加数据的实现 19.5.2 更新数据的实现 19.5.3 删除数据的实现 19.6 触发器与存储过程的应用 19.6.1 在C#应用触发器 19.6.2 在C#应用存储过程的示例 19.7 小结第20章 VB.NET与SQL Server的开发与应用 20.1 VB.NET介绍 20.1.1 了解VB.NET 20.1.2 VB.NET的新特点 20.2 VB.NET连接数据库 20.2.1 通过数据控件绑定连接数据库 20.2.2 通过数据对象直接连接数据库 20.3 数据查询应用 20.3.1 普通数据查询的实现 20.3.2 连接查询的实现隐藏全部目录>>
Exam Ref 70-761 Querying Data with Transact-SQL by Itzik Ben-Gan English | 4 Apr. 2017 | ASIN: B06Y21QGGQ | 352 Pages | AZW3 | 23.79 MB Prepare for Microsoft Exam 70-761–and help demonstrate your real-world mastery of SQL Server 2016 Transact-SQL data management, queries, and database programming. Designed for experienced IT professionals ready to advance their status, Exam Ref focuses on the critical-thinking and decision-making acumen needed for success at the MCSA level. Focus on the expertise measured by these objectives: • Filter, sort, join, aggregate, and modify data • Use subqueries, table expressions, grouping sets, and pivoting • Query temporal and non-relational data, and output XML or JSON • Create views, user-defined functions, and stored procedures • Implement error handling, transactions, data types, and nulls This Microsoft Exam Ref: • Organizes its coverage by exam objectives • Features strategic, what-if scenarios to challenge you • Assumes you have experience working with SQL Server as a database administrator, system engineer, or developer • Includes downloadable sample database and code for SQL Server 2016 SP1 (or later) and Azure SQL Database Querying Data with Transact-SQL About the Exam Exam 70-761 focuses on the skills and knowledge necessary to manage and query data and to program databases with Transact-SQL in SQL Server 2016. About Microsoft Certification Passing this exam earns you credit toward a Microsoft Certified Solutions Associate (MCSA) certification that demonstrates your mastery of essential skills for building and implementing on-premises and cloud-based databases across organizations. Exam 70-762 (Developing SQL Databases) is also required for MCSA: SQL 2016 Database Development certification. See full details at: microsoft.com/learning
Microsoft SQL Server 2005 Express Edition SQL Server 文档小组无法回答技术支持问题,但是欢迎您对本自述文档提出建议和意见。您可以使用提供的链接快速、直接地发送电子邮件反馈。请使用英语发送您的反馈信息。 若要通过邮件提交有关本文档的反馈信息,请单击此处:提交反馈。 目录 1.0 简介 2.0 下载并安装 SQL Server Express 2.1 .NET Framework 2.0 2.2 SQL Server Express 2.3 SQL Server Express 的管理工具 2.4 访问安装文档 2.5 SQL Server 2005 自述文件 3.0 安装问题 4.0 其他信息 4.1 服务帐户和网络协议 4.2 用户实例功能 4.3 WMI 提供程序和用户实例功能 4.4 联机丛书 4.5 获取 SQL Server Express 帮助 4.6 新闻组支持 4.7 提供有关 SQL Server Express 的反馈 5.0 数据库引擎 6.0 复制 [顶部] 1.0 简介 Microsoft SQL Server 2005 Express Edition (SQL Server Express) 是一个免费且易于使用的 SQL Server 2005 版本,它替换了 Microsoft Desktop Engine (MSDE)。与 Microsoft Visual Studio 2005 集成之后,SQL Server Express 可以轻松的开发功能强大且安全的数据驱动应用程序,并允许快速部署这些应用程序。SQL Server Express 可以根据协议重新进行发布,并可作为客户端数据库以及基本服务器数据库使用。SQL Server Express 是独立软件供应商 (ISV)、服务器用户、非专业开发人员、Web 应用程序开发人员、网站宿主以及客户端应用程序编程爱好者的理想之选。 未及时包括在本自述文件的任何有关 SQL Server Express 的信息都将发布到 Microsoft 知识库文章 907284 。 有关使用 SQL Server Express 新闻组提供反馈的信息,请参阅 4.6 新闻组支持部分。 [顶部] 2.0 下载并安装 SQL Server Express 本节介绍有关安装 .NET Framework 2.0、SQL Server Express 以及可用于连接到 SQL Server Express 的工具的信息。 2.1 .NET Framework 2.0 在安装 SQL Server Express 之前,必须安装 .NET Framework 2.0。 SQL Server Express 依赖于特定 2.0 版本的 .NET Framework。如果您已安装了其他版本的 .NET Framework,则 SQL Server Express 安装可能会在运行时发生意外情况。您可以从此 Microsoft 网站下载 .NET Framework 2.0。 注意: .NET Framework 2.0 由 Microsoft Visual Studio 2005 和所有版本的 SQL Server 2005 自动安装。 [顶部] 2.2 SQL Server Express SQL Server Express 可从此 Microsoft 网站下载获得。 注意: 下载和提取产品时,请务必按照下载站点提供的说明进行操作。 安装 SQL Server Express 之后,请在命令提示符下使用以下命令连接到 SQL Server Express: sqlcmd -S Server\Instance 其 Server 是计算机名称,Instance 是要连接到的实例名称。如果已在安装过程使用了默认的命名实例,则将实例指定为“SQLExpress”。 [顶部] 2.3 管理 SQL Server Express 的工具 有关连接到 SQL Server Express 数据库并进行管理的信息,请参阅 Microsoft 知识库文章 907716。 [顶部] 2.4 访问安装文档 SQL Server Express 的安装要求文档概述了硬件和软件要求。 [顶部] 2.5 SQL Server 2005 自述文件 SQL Server 2005 自述文件可以从此 Microsoft 网站在线获取。 注意: 未及时包括在本自述文件的任何有关 SQL Server 2005 和 SQL Server Express 的信息都将发布到 Microsoft 知识库文章 907284 。 [顶部] 3.0 安装问题 本部分详细介绍此版本的安装问题。 3.1 现有的 SQL 本机客户端安装可能导致安装失败 安装可能失败并回滚,同时显示以下错误消息:“找不到产品 Microsoft SQL 本机客户端的安装包。请使用安装包 sqlncli.msi 的有效副本重试安装。”若要解决此问题,请使用“添加或删除程序”卸载 SQL 本机客户端。对于群集,请从所有节点卸载 SQL 本机客户端。然后,再次运行 SQL Server 安装程序。 [顶部] 3.2 系统配置检查器失败并显示“性能监视器计数器检查失败”消息 在开始安装 SQL Server 之前,系统配置检查器 (SCC) 会验证性能监视器计数器注册表项的值。如果 SCC 无法验证现有的注册表项,或者 SCC 无法运行 Lodctr.exe 系统程序,则 SCC 检查会失败,并且安装程序会被阻止。若要完成安装,您必须手动增加注册表项。 注意: 如果注册表编辑不当,则可能会导致严重的问题并可能需要您重新安装操作系统。Microsoft 不保证可以解决因注册表编辑不当而导致的问题。在编辑注册表之前,请备份所有重要数据。有关如何备份、恢复和编辑注册表的信息,请参阅 Microsoft 知识库文章 256986。 若要手动增加计数器注册表项,请执行下列操作: 在任务栏,依次单击“开始”和“运行”,在“运行”文本框键入 regedit.exe,再单击“确定”。 导航到以下注册表项:[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib]。查找下列项: "Last Counter"=dword:00000ed4 (5276) "Last Help"=dword:00000ed5 (5277) 验证值。上一步 (5276) 的 Last Counter 值必须与以下注册表项内 Perflib\009 Counter 项的最大值相等,上一步 (5277) 的 Last Help 值必须与以下注册表项内 Perflib\009 Help 项的最大值相等:[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009]。 注意: “009”是用于英语(美国)的项。 如有必要,请修改 \Perflib 项 Last Counter 和 Last Help 的值。在右窗格,右键单击 Last Counter 或 Last Help,选择“修改”,单击 Base = Decimal,在“值”数据字段设置值,再单击“确定”。如有必要,请对其他项重复此操作,然后关闭注册表编辑器。 再次运行 SQL Server 2005 Express Edition 安装程序。 [顶部] 3.3 SQL Server Express 联机丛书包含关于操作系统支持的错误信息。 SQL Server Express 联机丛书的“硬件和软件要求 (SQL Server Express)”主题没有提供操作系统的精确列表。SQL Server Express 支持下列操作系统。 Windows Server 2003 SP1 Windows Server 2003 Enterprise Edition SP1 Windows Server 2003 Datacenter Edition SP1 Windows Small Business Server 2003 Standard Edition SP1 Windows Small Business Server 2003 Premium Edition SP1 Windows XP Professional SP2 Windows XP Home Edition SP2 Windows XP Tablet Edition SP2 Windows XP Media Edition SP2 Windows 2000 Professional Edition SP4 Windows 2000 Server Edition SP4 Windows 2000 Advanced Edition SP4 Windows 2000 Datacenter Server Edition SP4 [顶部] 3.4 如果在 Windows Server 2003 禁用了加密服务,则安装程序会失败并显示“Windows 徽标要求”对话框 Windows 加密服务提供程序 (CSP) 是执行身份验证、编码和加密服务的代码,基于 Windows 的应用程序通过 Windows Server 2003 的 CryptoAPI 访问这些服务。如果停止或禁用 CSP 服务,则 SQL Server 安装程序会失败并显示“Windows 徽标要求”消息。 注意: 在 Windows Server 2003 故障转移群集运行 SQL Server 安装程序之前,必须在所有群集节点上启动 CSP 服务。 若要在 Windows Server 2003 启用 Windows CSP 服务,请执行下列操作: 在“控制面板”,打开“管理工具”,再双击“服务”。 在“名称”列,右键单击“加密服务”,再单击“启动”。 关闭“服务”。 运行安装程序。 [顶部] 3.5 未在 Windows 完全启用 MSDTC 由于未在 Windows 完全配置 Microsoft 分布式事务处理协调器 (MS DTC),因此,应用程序可能无法在分布式事务登记 SQL Server Express 资源。此问题会影响使用分布式事务的链接服务器、分布式查询以及远程存储过程。为了避免出现此类问题,您必须在安装有 SQL Server Express 的服务器完全启用 MS DTC 服务。 若要完全启用 MS DTC,请执行下列操作: 在“控制面板”,打开“管理工具”,再双击“组件服务”。 在左窗格的“控制台根目录”,单击“组件服务”,再展开“计算机”。 右键单击“我的电脑”,再单击“属性”。 在 MSDTC 选项卡,单击“安全配置”。 在“安全设置”下,选所有复选框。 验证是否已将“DTC 登录帐户”名称设置为 NT AUTHORITY\NetworkService。 [顶部] 3.6 默认情况下不安装示例数据库 默认情况下,不在 SQL Server Express 安装示例数据库。Northwind 和 pubs 示例数据库可以从 Microsoft 网站进行下载。Adventureworks 示例数据库可从此 Microsoft 网站安装。 [顶部] 3.7“强制加密”配置可能会导致 SQL Server Express 安装程序失败 如果现有的 SQL Server 客户端安装配置为启用了“强制加密”选项,则安装程序可能会失败。若要解决此问题,请在所有 SQL Server 客户端上禁用此选项。对于 SQL Server 2000 的 Microsoft 数据访问组件 (MDAC) 客户端,请使用 SQL Server 2000 客户端网络实用工具。对于 SQL 本机客户端,请使用“添加或删除程序”卸载 SQL 本机客户端。在群集,请卸载所有节点的 SQL 本机客户端。然后,再次运行 SQL Server 2005 安装程序。 [顶部] 3.8 sp_configure 的设置可能会导致安装程序在升级系统数据库时失败 如果在更早 Community Technology Preview (CTP) 版本的 SQL Server Express 禁用了 sp_configure 选项“SMO 和 DMO XP”,则在使用 SAVESYSDB 卸载该早期实例,然后使用 USESYSDB 安装本版本时,将可能无法从命令提示符下进行安装。若要解决此问题,请确保在使用安装程序升级系统数据库之前,已启用上述选项。有关详细信息,请参阅此 Microsoft 网站上 SQL Server 联机丛书的“设置服务器配置选项”。 [顶部] 3.9 安装 SQL Server 2000 的默认实例可能会禁用 SQL Server Express 如果您的计算机已安装 SQL Server 2000 管理工具和 SQL Server Express 的默认实例,则可以使用 SQL Server 安装程序安装 SQL Server 2000 的默认实例。但是,这样做会禁用已安装的 SQL Server Express 实例。因此,如果计算机上已安装 SQL Server 2000 管理工具和 SQL Server Express 的默认实例,则不要安装 SQL Server 2000 的默认实例。 [顶部] 3.10 在 Windows 域控制器安装 SQL Server Express 安全说明: 我们不建议在域控制器运行 SQL Server Express。 可以在 Windows 域控制器安装 SQL Server Express;但是,SQL Server Express 无法在 Windows Server 2003 域控制器像本地服务或网络服务那样运行。SQL Server 服务帐户应以 Windows 域用户帐户的身份运行。您也可安装 SQL Server 服务帐户以本地系统的身份运行,但是不建议使用此选项。 不要在安装完 SQL Server Express 之后更改服务器的角色。例如,如果您在成员服务器安装了 SQL Server Express,则不要使用 Dcpromo 工具将该服务器提升为域控制器。或者,如果您在域控制器安装了 SQL Server Express,则不要使用 Dcpromo 将该服务器降级为成员服务器。如果在安装完 SQL Server Express 之后更改服务器的角色,便会导致功能丢失,不支持这样做。 [顶部] 3.11 现有的 SQL 本机客户端安装可能导致安装失败 安装可能失败并回滚,同时显示以下错误消息:“找不到产品 Microsoft SQL 本机客户端的安装包。请使用安装包 sqlncli.msi 的有效副本重试安装。”若要解决此问题,请使用“添加或删除程序”卸载 SQL 本机客户端。对于群集,请从所有节点卸载 SQL 本机客户端。然后,再次运行 SQL Server 安装程序。 [顶部] 3.12 卸载 SQL Server Express 和 Visual Studio 2005 的预发布版本 安装前,您必须删除 SQL Server Express、Visual Studio 2005 和 .NET Framework 2.0 的所有以前内部版本。由于这两个产品都依赖于相同版本的 .NET Framework,因此必须按照以下顺序卸载它们: SQL Server Express Visual Studio 2005 .NET Framework 2.0 [顶部] 3.13 维护模式下将提示输入 Setup.exe 的路径 如果在维护模式下安装新的 SQL Server 2005 组件,系统将提示您指定 SQL Server 2005 安装媒体 Setup.exe 文件的位置。指定该文件位置时,路径一定要包含“Setup.exe”。例如,路径“D:\”将失败,而“D:\Setup.exe”将成功。 [顶部] 3.14 Setup 命令 Shell 脚本的故障排除失败 路径变量包含括号时,Setup 命令 shell 脚本可以生成 Windows 脚本错误。出现该错误的原因是命令 shell 脚本不支持路径变量包含的括号。在将 32 位组件安装到 64 位计算机的 Windows (WOW64) 32 位子系统的 Windows 时可能会出现该错误。例如,下列路径值为“C:\Program Files (x86)\”的脚本将生成一个错误,因为 shell 脚本解释器会将扩展的 PATH 变量的括号错误地解释为 IF/ELSE 语句的一部分: IF "%SOME_PATH%" == "" ( SET PATH=%PATH%;%PATH_A% ) ELSE ( SET PATH=%PATH%;%PATH_B% ) 若要解决此问题,请更改该脚本以删除括号。例如: IF "%SOME_PATH%" == "" set PATH=%PATH%;%PATH_A% IF NOT "%SOME_PATH%" == "" set PATH=%PATH%;%PATH_B% 或者从路径删除包含括号的 SQL 项。 [顶部] 4.0 其他信息 4.1 服务帐户和网络协议 在 SQL Server Express ,本地系统帐户即为网络服务帐户。 SQL Server Express 可侦听本地命名管道和共享内存。执行默认安装时,无法远程连接到 SQL Server Express。您需要启用 TCP/IP 并检查是否已启用防火墙。 若要启用 TCP/IP,请执行下列操作: 在“开始”菜单,选择“所有程序”,依次指向 Microsoft SQL Server 2005 和“配置工具”,再单击“SQL Server 配置管理器”。 或者,您可以通过右键单击“我的电脑”并选择“管理”来打开计算机管理器。在“计算机管理”,依次展开“服务和应用程序”和“SQL Server 配置管理器”。 展开“SQL Server 2005 网络配置”,再单击“InstanceName 的协议”。 在协议列表,右键单击要启用的协议,再单击“启用”。 协议的图标将更改为显示该协议已启用。 若要启用防火墙,请执行下列操作: 依次单击“开始”和“控制面板”,再单击“网络连接”。 在左侧的导航栏,单击“更改 Windows 防火墙的设置”。 在“异常”选项卡的“程序和服务”框,您可能看到已列出 SQL Server,但未将其选择为异常。如果您选该复选框,则 Windows 将打开端口 1433 以允许 TCP 请求进入。或者,如果您未看到列出 SQL Server,则请执行下列操作: 单击“添加程序”。 单击“浏览”。 导航到 drive:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\BINN 将文件 sqlservr.exe 添加到异常列表。 [顶部] 4.2 用户实例功能 SQL Server Express 允许非管理员用户在没有 DBCreator 特权的情况下也能复制或移动数据库使用 Xcopy 部署)。有关详细信息,请参阅此 Microsoft 网站上的 SQL Server Express 联机丛书的“非管理员用户实例”。 [顶部] 4.3 WMI 提供程序和用户实例功能 动态生成的用户实例不支持 WMI Provider for Server Events。此程序仍运行于父 SQL Server Express 实例。 [顶部] 4.4 联机丛书 SQL Server Express 联机丛书可从此 Microsoft 网站下载获得。 注意: 由于 SQL Server Express 是 SQL Server 2005 的一个受限版本,因此,SQL Server Express 联机丛书的文档很大程度上依赖于 SQL Server 2005 联机丛书的内容。 SQL Server 2005 联机丛书可从此 Microsoft 网站下载获得。 Microsoft 定期发布 SQL Server Express 联机丛书和 SQL Server 2005 联机丛书的可下载更新。我们建议您安装这些更新以及时更新该文档的本地副本相应的信息。 [顶部] 4.5 获取 SQL Server Express 帮助 Microsoft 通过以下四个主要信息来源提供有关 SQL Server Express 的信息: SQL Server Express 文档和示例 SQL Server 2005 文档 Microsoft Developer Network (MSDN) 和 TechNet 上的 SQL Server 站点 其他 Microsoft 网站上的 SQL Server 信息 您也可以通过 SQL Server 社区从其他人或直接从 Microsoft 支持人员处获取帮助。有关详细信息,请参阅 SQL Server Express 联机丛书的“获取 SQL Server Express 帮助”。 [顶部] 4.6 新闻组支持 有关新闻组支持的信息,请从此 Microsoft 网站访问 SQL Server Express 新闻组。请不要使用其他 Microsoft 新闻组张贴有关 SQL Server Express 的问题。 可在 SQL Server Express 网站日志找到来自 SQL Server Express 小组的最新信息。 注意: 仅支持英语版的新闻组。 [顶部] 4.7 提供有关 SQL Server Express 的反馈 可通过下列方式提供有关 SQL Server Express 的建议和错误报告: 在此 Microsoft 网站发送有关 SQL Server Express 的功能和用户界面的建议和错误报告。 使用 SQL Server Express 联机丛书的反馈功能发送有关文档的建议以及报告其不正确的内容。 选择自动将错误报告和功能使用情况数据发送给 Microsoft 进行分析。 有关详细信息,请参阅 SQL Server 联机丛书的“提供有关 SQL Server 2005 的反馈”。 [顶部] 5.0 数据库引擎 本部分说明 SQL Server 2005 数据库引擎和数据库引擎特定的命令提示实用工具的最新项,这些最新项也应用于 SQL Server Express。 [顶部] 5.1 在 Windows Server 2003 SP1 运行时连接可能会被强行关闭 如果 TCP/IP 网络处于打开状态,则指向 Windows Server 2003 Service Pack 1 运行的 SQL Server Express 数据库引擎实例的客户端连接可能会失败,并出现以下错误:“提供程序号: 7,错误: 10054,错误消息:‘TCP 提供程序: 现有连接被远程主机强行关闭’”。 如果要通过大量客户端连接尝试来测试可伸缩性,则可能会出现此错误。若要解决此问题,请使用 regedit.exe 实用工具将名为 SynAttackProtect 的新 DWORD 值添加到注册表项 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\(值数据为 00000000)。 安全说明: 设置此注册表项可能会使服务器受到 SYN Flood 拒绝服务攻击。测试完成时,请删除该注册表值。 注意: 如果注册表编辑不当,可能会导致严重问题并可能需要重新安装操作系统。Microsoft 不保证可以解决因注册表编辑不当而导致的问题。在编辑注册表之前,请备份所有重要数据。有关如何备份、恢复和编辑注册表的信息,请参阅 Microsoft 知识库文章 256986。 [顶部] 5.2 安全的 Service Broker 对话需要数据库主密钥 SQL Server 2005 联机丛书错误地说明了当跨数据库使用对话安全设置进行会话时,SQL Server 会创建通过数据库主密钥加密的会话密钥。实际上,对于所有使用对话安全设置进行的会话而言,会话密钥均通过数据库主密钥进行加密。如果数据库主密钥不可用,则在创建数据库主密钥或会话超时之前,会话的消息将一直保留在 transmission_queue 并出现错误。您可以使用 ENCRYPTION = OFF 参数创建未加密的对话,也可以使用以下命令创建数据库主密钥: CREATE MASTER KEY ENCRYPTION BY PASSWORD = '' [顶部] 5.3 公共语言运行时用户定义类型应只有一个序列化 每个字节顺序的用户定义类型 (UDT) 对象的实例只能有一种序列化表示形式。如果序列化或反序列化例程识别出某个特定对象具有多种表示形式,则可能会在下列情况下出现错误: 在验证通过 RPC 传递的字节顺序的 UDT 期间,UDT 验证执行 UDT 的反序列化/重新序列化,并要求生成的字节与原始字节完全相同。如果验证失败,则会出现错误:“System.Data.SqlClient.SqlException,传入的 TDS RPC 协议流不正确。参数 1 (""):提供的值不是数据类型 的有效实例。请检查源数据的无效值。” 在 DBCC 期间,字节顺序的 UDT 列存储的字节数必须等于计算的 UDT 值序列化。如果不相等,则 DBCC CHECKTABLE 例程将会报告一致性错误。 [顶部] 5.4 尚未通过设置启用网络连接 为了提高安全性,SQL Server Express 针对某些新安装禁用了网络连接。如果您使用的是 SQL Server Enterprise Edition、Standard Edition 或 Workgroup Edition,或计算机上已经安装有 SQL Server,则不会禁用使用 TCP/IP 协议的网络连接。除非计算机上已经安装有 SQL Server,否则 Named Pipes 连接仅适用于本地连接。对于所有安装,都会启用 Shared Memory 协议,以允许服务器的本地连接。根据具体的安装条件和安装选项,可能会停止 SQL Browser 服务。 [顶部] 5.5 包含用户定义类型的程序集注意事项 下列限制适用于包含用户定义类型的公共语言运行时 (CLR) 程序集。 公共语言运行时用户定义类型只能有一个序列化 字节顺序的用户定义类型对象的各个实例只能有一种序列化表示形式。如果序列化或反序列化例程检测到某个特定对象具有多种表示形式,则在以下情况下可能会显示错误: 在验证通过 RPC 传递的字节顺序的用户定义类型的过程,用户定义类型验证过程会对该用户定义类型执行反序列化/重新序列化,并要求生成的字节与原始字节完全相同。如果验证失败,您将看到以下错误:“System.Data.SqlClient.SqlException,传入的 TDS RPC 协议流不正确。参数 1 (""): 提供的值不是数据类型 的有效实例。请检查源数据的无效值。” 在 DBCC CHECKTABLE 过程,在字节顺序的用户定义类型列存储的字节必须与计算出的 UDT 值的序列化表示形式相同。如果不相同,则 DBCC CHECKTABLE 例程将报告一个一致性错误。 有关更新带有用户定义类型类的程序集的已更新的限制 可以按下列方式使用 ALTER ASSEMBLY 更新 CLR 用户定义类型: 修改用户定义类型类的公共方法,但不更改签名或属性。 添加新的公共方法。 以任何方式修改私有方法使用 ALTER ASSEMBLY 不能更改本机序列化的用户定义类型包含的字段,包括数据成员和基类。不支持所有其他更改。 [顶部] 5.6 SQL Server 不保证更新程序集时的数据一致性 如未指定 WITH UNCHECKED DATA,则在新的程序集版本对表、索引或其他持久站点的现有数据产生影响时,SQL Server 将会阻止执行 ALTER ASSEMBLY。更新公共语言运行时 (CLR) 程序集时,SQL Server 并不保证计算列、索引、索引视图或表达式与基础例程和类型保持一致。执行 ALTER ASSEMBLY 时需谨慎操作,以确保在表达式结果和基于存储在程序集的该表达式的值之间没有不匹配。 [顶部] 5.7 卷影复制服务的快照自动恢复功能的注意事项 卷影复制服务 (VSS) 的快照自动恢复功能具有下列限制。 多个持续自动恢复的快照 在 Windows Server 2003 Service Pack 1 (SP1) 和更高版本,您只能创建单个持续自动恢复的快照。若要创建其他快照,您必须首先应用知识库文章 891957 所述的更新。 注意: 如果尚未应用此更新,则可以通过以下方式创建新的持续自动恢复的快照:首先删除现有的持续自动恢复的快照,然后创建一个新的持续自动恢复的快照。 自动恢复的快照和全文目录 快照自动恢复功能不支持全文目录。创建自动恢复的快照之后,在该快照数据库的所有全文目录都将处于脱机状态。在从快照附加数据库时,全文目录会永久保持脱机状态。但附加的数据库的其他所有数据均可用。 在从自动恢复的快照直接附加包含全文目录的数据库时,附加操作将返回以下错误消息: Server: Msg 7608, Level 17, State 1, Line 1 An unknown full-text failure (0xc000000d) occurred during "Mounting a full-text catalog". 如果不需要直接从快照附加数据库,则可以通过如下方式来避免此问题:先将快照数据库文件和全文目录复制到基于驱动器号的常规卷,然后从该位置附加数据库。只要附加命令指定了所复制的全文文件的正确位置,即可正常使用这些全文目录。 [顶部] 5.8 注册公共语言运行时程序集的限制 SQL Server 不允许使用相同的名称、区域性和公钥注册程序集的不同版本。如果计划保留九月份 CTP 版本之前的 SQL Server Express 版本数据库,则在安装该版本之前,必须删除具有多个注册的程序集的所有其他实例,只保留一个实例。 [顶部] 5.9 创建 EXTERNAL_ACCESS 和 UNSAFE 程序集 若要在 SQL Server 创建 EXTERNAL_ACCESS 或 UNSAFE 程序集或者要加载程序集,必须满足下列两个条件之一: 程序集经过强名称签名或使用证书进行了 authenticode 签名。此强名称(或证书)在 SQL Server 作为非对称密钥(或证书)创建,并具有相应的登录名,该登录名具有 EXTERNAL ACCESS ASSEMBLY 权限(对于 EXTERNAL ACCESS 程序集)或 UNSAFE ASSEMBLY 权限(对于 UNSAFE 程序集)。 数据库所有者 (DBO) 具有 EXTERNAL ACCESS ASSEMBLY(对于 EXTERNAL ACCESS 程序集)或 UNSAFE ASSEMBLY(对于 UNSAFE 程序集)权限,并且该数据库的 TRUSTWORTHY 属性设置为 ON。 除了要在服务器进程运行公共语言运行时 (CLR) 代码之外,建议始终将数据库的 TRUSTWORTHY 属性设置为 ON。并且建议通过 master 数据库的程序集文件创建非对称密钥。然后,必须创建映射到此非对称密钥的登录名,并且为该登录名授予 EXTERNAL ACCESS ASSEMBLY 或 UNSAFE ASSEMBLY 权限。 下面的 Transact-SQL 语句将执行完成下列操作所需的步骤:创建非对称密钥,将一个登录名映射到此密钥,然后为该登录名授予 EXTERNAL_ACCESS ASSEMBLY 权限。必须在执行 CREATE ASSEMBLY 语句之前执行下面的 Transact-SQL 语句: USE master GO CREATE ASYMMETRIC KEY HelloWorldKey FROM EXECUTABLE FILE = 'C:\HelloWorld.dll' CREATE LOGIN HelloWorldLogin FROM ASYMMETRIC KEY HelloWorldKey GRANT EXTERNAL ACCESS ASSEMBLY TO HelloWorldLogin GO [顶部] 5.10 应用程序角色与元数据可见性限制以及动态管理视图的兼容性 在某个应用程序角色下运行的程序的行为可能会发生更改,因为在默认情况下,SQL Server Express 将限制 master 数据库元数据对于应用程序角色的可见性。作为临时解决方法,您可以启用跟踪标志 #4616。有关详细信息,请参阅知识库文章 906549。 [顶部] 5.11 未实现 SUPPLEMENTAL_LOGGING 数据库选项 在此版本的 SQL Server 未实现 SUPPLEMENTAL_LOGGING 数据库选项。此选项可以设置,但不起任何作用。 [顶部] 5.12 sys.dm_clr_loaded_assemblies 显示无法加载的程序集 由于任何原因未能加载到服务器地址空间的程序集仍将显示在 sys.dm_clr_loaded_assemblies 动态管理视图。 [顶部] 5.13 XQuery 更改 联机丛书未说明 SQL Server Express XQuery 实现的以下几个方面: 没有将 CDATA 部分生成的字符视为空格字符。例如,select cast(''as xml).query(' <![CDATA[ ]]> {"abc"}') 返回 abc。 支持构造空元素和空属性。 命名空间前缀 xmlns 用于标识命名空间声明属性,不能在 XQuery 表达式重新声明。这是 XQuery 规范要求的行为。 将“for”与源表达式 () 一起使用会生成一个静态的错误。 在使用 xml 数据类型的 query() 方法构造的 XML 文档,CDATA 部分的回车符变为换行符。为了进行文本 XML 分析,使用换行符代替之前的回车符实体引用 ( )。 包含 local-name() 和 namespace-uri() 的 Transact-SQL 用户定义函数为确定性函数。 [顶部] 5.14 xsd:dateTime 转换的限制比所述限制更少 不包含日期和时间分隔符 T 或时区的 xs:dateTime 值的字符串表示可以在 value() 方法转换为 SQL datetime 类型,如以下示例所示: declare @aaa xml set @aaa = '' select @aaa.value('(//AAA)[1]/@MyDate', 'datetime') [顶部] 5.15 XML 架构支持 SQL Server 2005 联机丛书未说明 SQL Server 2005 对 XML 架构以下几个方面的支持: 可以将 Reporting Services (RDL) 的 XML 架构加载到 XML 架构集合。 如果 xs:dateTime 和 xs:time 类型的值包含具有三个以上小数位数的副值,则这些值不会返回错误,而是会被进行舍入。 当基类型具有 fixed="true" 时,如果在派生类型重新定义 maxInclusive,便会拒绝使用 XML 架构。 限制 xs:dateTime、xs:data 和 xs:time 等数据类型的派生类型将忽略 minInclusive、minExclusive、maxInclusive 和 maxExclusive 部分的尾随空格。 [顶部] 5.16 不应使用 RC4 加密 请勿使用 RC4 加密保护 SQL Server 2005 的数据,而改为使用分组密码,如 AES 256 或 Triple DES。 [顶部] 6.0 复制 本部分介绍了有关复制的最新信息。 [顶部] 默认情况下禁用复制功能 Microsoft SQL Server 2005 Express Edition 可以用作所有复制类型的订阅服务器,但是默认情况下不会为此版本安装复制功能。 若要安装复制组件,请执行下列操作: 在“功能选择”页,展开“数据库服务”。 单击“复制”,再单击“整个功能将被安装在本地硬盘上”。 若要安装连接组件和复制管理对象 (RMO),请执行下列操作: 在“功能选择”页,单击“客户端组件”,再单击“整个功能将被安装在本地硬盘上”。 [顶部] © 2005 Microsoft Corporation。保留所有权利。
Contents Overview 1 Lesson 1: Concepts – Locks and Lock Manager 3 Lesson 2: Concepts – Batch and Transaction 31 Lesson 3: Concepts – Locks and Applications 51 Lesson 4: Information Collection and Analysis 63 Lesson 5: Concepts – Formulating and Implementing Resolution 81 Module 4: Troubleshooting Locking and Blocking Overview At the end of this module, you will be able to:  Discuss how lock manager uses lock mode, lock resources, and lock compatibility to achieve transaction isolation.  Describe the various transaction types and how transactions differ from batches.  Describe how to troubleshoot blocking and locking issues.  Analyze the output of blocking scripts and Microsoft® SQL Server™ Profiler to troubleshoot locking and blocking issues.  Formulate hypothesis to resolve locking and blocking issues. Lesson 1: Concepts – Locks and Lock Manager This lesson outlines some of the common causes that contribute to the perception of a slow server. What You Will Learn After completing this lesson, you will be able to:  Describe locking architecture used by SQL Server.  Identify the various lock modes used by SQL Server.  Discuss lock compatibility and concurrent access.  Identify different types of lock resources.  Discuss dynamic locking and lock escalation.  Differentiate locks, latches, and other SQL Server internal “locking” mechanism such as spinlocks and other synchronization objects. Recommended Reading  Chapter 14 “Locking”, Inside SQL Server 2000 by Kalen Delaney  SOX000821700049 – SQL 7.0 How to interpret lock resource Ids  SOX000925700237 – TITLE: Lock escalation in SQL 7.0  SOX001109700040 – INF: Queries with PREFETCH in the plan hold lock until the end of transaction Locking Concepts Delivery Tip Prior to delivering this material, test the class to see if they fully understand the different isolation levels. If the class is not confident in their understanding, review appendix A04_Locking and its accompanying PowerPoint® file. Transactions in SQL Server provide the ACID properties: Atomicity A transaction either commits or aborts. If a transaction commits, all of its effects remain. If it aborts, all of its effects are undone. It is an “all or nothing” operation. Consistency An application should maintain the consistency of a database. For example, if you defer constraint checking, it is your responsibility to ensure that the database is consistent. Isolation Concurrent transactions are isolated from the updates of other incomplete transactions. These updates do not constitute a consistent state. This property is often called serializability. For example, a second transaction traversing the doubly linked list mentioned above would see the list before or after the insert, but it will see only complete changes. Durability After a transaction commits, its effects will persist even if there are system failures. Consistency and isolation are the most important in describing SQL Server’s locking model. It is up to the application to define what consistency means, and isolation in some form is needed to achieve consistent results. SQL Server uses locking to achieve isolation. Definition of Dependency: A set of transactions can run concurrently if their outputs are disjoint from the union of one another’s input and output sets. For example, if T1 writes some object that is in T2’s input or output set, there is a dependency between T1 and T2. Bad Dependencies These include lost updates, dirty reads, non-repeatable reads, and phantoms. ANSI SQL Isolation Levels An isolation level determines the degree to which data is isolated for use by one process and guarded against interference from other processes. Prior to SQL Server 7.0, REPEATABLE READ and SERIALIZABLE isolation levels were synonymous. There was no way to prevent non-repeatable reads while not preventing phantoms. By default, SQL Server 2000 operates at an isolation level of READ COMMITTED. To make use of either more or less strict isolation levels in applications, locking can be customized for an entire session by setting the isolation level of the session with the SET TRANSACTION ISOLATION LEVEL statement. To determine the transaction isolation level currently set, use the DBCC USEROPTIONS statement, for example: USE pubs GO SET TRANSACTION ISOLATION LEVEL REPEATABLE READ GO DBCC USEROPTIONS GO Multigranular Locking Multigranular Locking In our example, if one transaction (T1) holds an exclusive lock at the table level, and another transaction (T2) holds an exclusive lock at the row level, each of the transactions believe they have exclusive access to the resource. In this scenario, since T1 believes it locks the entire table, it might inadvertently make changes to the same row that T2 thought it has locked exclusively. In a multigranular locking environment, there must be a way to effectively overcome this scenario. Intent lock is the answer to this problem. Intent Lock Intent Lock is the term used to mean placing a marker in a higher-level lock queue. The type of intent lock can also be called the multigranular lock mode. An intent lock indicates that SQL Server wants to acquire a shared (S) lock or exclusive (X) lock on some of the resources lower down in the hierarchy. For example, a shared intent lock placed at the table level means that a transaction intends on placing shared (S) locks on pages or rows within that table. Setting an intent lock at the table level prevents another transaction from subsequently acquiring an exclusive (X) lock on the table containing that page. Intent locks improve performance because SQL Server examines intent locks only at the table level to determine whether a transaction can safely acquire a lock on that table. This removes the requirement to examine every row or page lock on the table to determine whether a transaction can lock the entire table. Lock Mode The code shown in the slide represents how the lock mode is stored internally. You can see these codes by querying the master.dbo.spt_values table: SELECT * FROM master.dbo.spt_values WHERE type = N'L' However, the req_mode column of master.dbo.syslockinfo has lock mode code that is one less than the code values shown here. For example, value of req_mode = 3 represents the Shared lock mode rather than the Schema Modification lock mode. Lock Compatibility These locks can apply at any coarser level of granularity. If a row is locked, SQL Server will apply intent locks at both the page and the table level. If a page is locked, SQL Server will apply an intent lock at the table level. SIX locks imply that we have shared access to a resource and we have also placed X locks at a lower level in the hierarchy. SQL Server never asks for SIX locks directly, they are always the result of a conversion. For example, suppose a transaction scanned a page using an S lock and then subsequently decided to perform a row level update. The row would obtain an X lock, but now the page would require an IX lock. The resultant mode on the page would be SIX. Another type of table lock is a schema stability lock (Sch-S) and is compatible with all table locks except the schema modification lock (Sch-M). The schema modification lock (Sch-M) is incompatible with all table locks. Locking Resources Delivery Tip Note the differences between Key and Key Range locks. Key Range locks will be covered in a couple of slides. SQL Server can lock these resources: Item Description DB A database. File A database file Index An entire index of a table. Table An entire table, including all data and indexes. Extent A contiguous group of data pages or index pages. Page An 8-KB data page or index page. Key Row lock within an index. Key-range A key-range. Used to lock ranges between records in a table to prevent phantom insertions or deletions into a set of records. Ensures serializable transactions. RID A Row Identifier. Used to individually lock a single row within a table. Application A lock resource defined by an application. The lock manager knows nothing about the resource format. It simply compares the 'strings' representing the lock resources to determine whether it has found a match. If a match is found, it knows that resource is already locked. Some of the resources have “sub-resources.” The followings are sub-resources displayed by the sp_lock output: Database Lock Sub-Resources: Full Database Lock (default) [BULK-OP-DB] – Bulk Operation Lock for Database [BULK-OP-LOG] – Bulk Operation Lock for Log Table Lock Sub-Resources: Full Table Lock (default) [UPD-STATS] – Update statistics Lock [COMPILE] – Compile Lock Index Lock sub-Resources: Full Index Lock (default) [INDEX_ID] – Index ID Lock [INDEX_NAME] – Index Name Lock [BULK_ALLOC] – Bulk Allocation Lock [DEFRAG] – Defragmentation Lock For more information, see also… SOX000821700049 SQL 7.0 How to interpret lock resource Ids Lock Resource Block The resource type has the following resource block format: Resource Type (Code) Content DB (2) Data 1: sub-resource; Data 2: 0; Data 3: 0 File (3) Data 1: File ID; Data 2: 0; Data 3: 0 Index (4) Data 1: Object ID; Data 2: sub-resource; Data 3: Index ID Table (5) Data 1: Object ID; Data 2: sub-resource; Data 3: 0. Page (6) Data 1: Page Number; Data 3: 0. Key (7) Data 1: Object ID; Data 2: Index ID; Data 3: Hashed Key Extent (8) Data 1: Extent ID; Data 3: 0. RID (9) Data 1: RID; Data 3: 0. Application (10) Data 1: Application resource name The rsc_bin column of master..syslockinfo contains the resource block in hexadecimal format. For an example of how to decode value from this column using the information above, let us assume we have the following value: 0x000705001F83D775010002014F0BEC4E With byte swapping within each field, this can be decoded as: Byte 0: Flag – 0x00 Byte 1: Resource Type – 0x07 (Key) Byte 2-3: DBID – 0x0005 Byte 4-7: ObjectID – 0x 75D7831F (1977058079) Byte 8-9: IndexID – 0x0001 Byte 10-16: Hash Key value – 0x 02014F0BEC4E For more information about how to decode this value, see also… Inside SQL Server 2000, pages 803 and 806. Key Range Locking Key Range Locking To support SERIALIZABLE transaction semantics, SQL Server needs to lock sets of rows specified by a predicate, such as WHERE salary BETWEEN 30000 AND 50000 SQL Server needs to lock data that does not exist! If no rows satisfy the WHERE condition the first time the range is scanned, no rows should be returned on any subsequent scans. Key range locks are similar to row locks on index keys (whether clustered or not). The locks are placed on individual keys rather than at the node level. The hash value consists of all the key components and the locator. So, for a nonclustered index over a heap, where columns c1 and c2 where indexed, the hash would contain contributions from c1, c2 and the RID. A key range lock applied to a particular key means that all keys between the value locked and the next value would be locked for all data modification. Key range locks can lock a slightly larger range than that implied by the WHERE clause. Suppose the following select was executed in a transaction with isolation level SERIALIZABLE: SELECT * FROM members WHERE first_name between ‘Al’ and ‘Carl’ If 'Al', 'Bob', and 'Dave' are index keys in the table, the first two of these would acquire key range locks. Although this would prevent anyone from inserting either 'Alex' or 'Ben', it would also prevent someone from inserting 'Dan', which is not within the range of the WHERE clause. Prior to SQL Server 7.0, page locking was used to prevent phantoms by locking the entire set of pages on which the phantom would exist. This can be too conservative. Key Range locking lets SQL Server lock only a much more restrictive area of the table. Impact Key-range locking ensures that these scenarios are SERIALIZABLE:  Range scan query  Singleton fetch of nonexistent row  Delete operation  Insert operation However, the following conditions must be satisfied before key-range locking can occur:  The transaction-isolation level must be set to SERIALIZABLE.  The operation performed on the data must use an index range access. Range locking is activated only when query processing (such as the optimizer) chooses an index path to access the data. Key Range Lock Mode Again, the req_mode column of master.dbo.syslockinfo has lock mode code that is one less than the code values shown here. Dynamic Locking When modifying individual rows, SQL Server typically would take row locks to maximize concurrency (for example, OLTP, order-entry application). When scanning larger volumes of data, it would be more appropriate to take page or table locks to minimize the cost of acquiring locks (for example, DSS, data warehouse, reporting). Locking Decision The decision about which unit to lock is made dynamically, taking many factors into account, including other activity on the system. For example, if there are multiple transactions currently accessing a table, SQL Server will tend to favor row locking more so than it otherwise would. It may mean the difference between scanning the table now and paying a bit more in locking cost, or having to wait to acquire a more coarse lock. A preliminary locking decision is made during query optimization, but that decision can be adjusted when the query is actually executed. Lock Escalation When the lock count for the transaction exceeds and is a multiple of ESCALATION_THRESHOLD (1250), the Lock Manager attempts to escalate. For example, when a transaction acquired 1250 locks, lock manager will try to escalate. The number of locks held may continue to increase after the escalation attempt (for example, because new tables are accessed, or the previous lock escalation attempts failed due to incompatible locks held by another spid). If the lock count for this transaction reaches 2500 (1250 * 2), Lock Manager will attempt escalation again. The Lock Manager looks at the lock memory it is using and if it is more than 40 percent of SQL Server’s allocated buffer pool memory, it tries to find a scan (SDES) where no escalation has already been performed. It then repeats the search operation until all scans have been escalated or until the memory used drops under the MEMORY_LOAD_ESCALATION_THRESHOLD (40%) value. If lock escalation is not possible or fails to significantly reduce lock memory footprint, SQL Server can continue to acquire locks until the total lock memory reaches 60 percent of the buffer pool (MAX_LOCK_RESOURCE_MEMORY_PERCENTAGE=60). Lock escalation may be also done when a single scan (SDES) holds more than LOCK_ESCALATION_THRESHOLD (765) locks. There is no lock escalation on temporary tables or system tables. Trace Flag 1211 disables lock escalation. Important Do not relay this to the customer without careful consideration. Lock escalation is a necessary feature, not something to be avoided completely. Trace flags are global and disabling lock escalation could lead to out of memory situations, extremely poor performing queries, or other problems. Lock escalation tracing can be seen using the Profiler or with the general locking trace flag, -T1200. However, Trace Flag 1200 shows all lock activity so it should not be usable on a production system. For more information, see also… SOX000925700237 “TITLE: SQL 7.0 Lock escalation in SQL 7.0” Lock Timeout Application Lock Timeout An application can set lock timeout for a session with the SET option: SET LOCK_TIMEOUT N where N is a number of milliseconds. A value of -1 means that there will be no timeout, which is equivalent to the version 6.5 behavior. A value of 0 means that there will be no waiting; if a process finds a resource locked, it will generate error message 1222 and continue with the next statement. The current value of LOCK_TIMEOUT is stored in the global variable @@lock_timeout. Note After a lock timeout any transaction containing the statement, is rolled back or canceled by SQL Server 2000 (bug#352640 was filed). This behavior is different from that of SQL Server 7.0. With SQL Server 7.0, the application must have an error handler that can trap error 1222 and if an application does not trap the error, it can proceed unaware that an individual statement within a transaction has been canceled, and errors can occur because statements later in the transaction may depend on the statement that was never executed. Bug#352640 is fixed in hotfix build 8.00.266 whereby a lock timeout will only Internal Lock Timeout At time, internal operations within SQL Server will attempt to acquire locks via lock manager. Typically, these lock requests are issued with “no waiting.” For example, the ghost record processing might try to clean up rows on a particular page, and before it can do that, it needs to lock the page. Thus, the ghost record manager will request a page lock with no wait so that if it cannot lock the page, it will just move on to other pages; it can always come back to this page later. If you look at SQL Profiler Lock: Timeout events, internal lock timeout typically have a duration value of zero. Lock Duration Lock Mode and Transaction Isolation Level For REPEATABLE READ transaction isolation level, update locks are held until data is read and processed, unless promoted to exclusive locks. "Data is processed" means that we have decided whether the row in question matched the search criteria; if not then the update lock is released, otherwise, we get an exclusive lock and make the modification. Consider the following query: use northwind go dbcc traceon(3604, 1200, 1211) -- turn on lock tracing -- and disable escalation go set transaction isolation level repeatable read begin tran update dbo.[order details] set discount = convert (real, discount) where discount = 0.0 exec sp_lock Update locks are promoted to exclusive locks when there is a match; otherwise, the update lock is released. The sp_lock output verifies that the SPID does not hold any update locks or shared locks at the end of the query. Lock escalation is turned off so that exclusive table lock is not held at the end. Warning Do not use trace flag 1200 in a production environment because it produces a lot of output and slows down the server. Trace flag 1211 should not be used unless you have done extensive study to make sure it helps with performance. These trace flags are used here for illustration and learning purposes only. Lock Ownership Most of the locking discussion in this lesson relates to locks owned by “transactions.” In addition to transaction, cursor and session can be owners of locks and they both affect how long locks are held. For every row that is fetched, when SCROLL_LOCKS option is used, regardless of the state of a transaction, a cursor lock is held until the next row is fetched or when the cursor is closed. Locks owned by session are outside the scope of a transaction. The duration of these locks are bounded by the connection and the process will continue to hold these locks until the process disconnects. A typical lock owned by session is the database (DB) lock. Locking – Read Committed Scan Under read committed isolation level, when database pages are scanned, shared locks are held when the page is read and processed. The shared locks are released “behind” the scan and allow other transactions to update rows. It is important to note that the shared lock currently acquired will not be released until shared lock for the next page is successfully acquired (this is commonly know as “crabbing”). If the same pages are scanned again, rows may be modified or deleted by other transactions. Locking – Repeatable Read Scan Under repeatable read isolation level, when database pages are scanned, shared locks are held when the page is read and processed. SQL Server continues to hold these shared locks, thus preventing other transactions to update rows. If the same pages are scanned again, previously scanned rows will not change but new rows may be added by other transactions. Locking – Serializable Read Scan Under serializable read isolation level, when database pages are scanned, shared locks are held not only on rows but also on scanned key range. SQL Server continues to hold these shared locks until the end of transaction. Because key range locks are held, not only will this prevent other transactions from modifying the rows, no new rows can be inserted. Prefetch and Isolation Level Prefetch and Locking Behavior The prefetch feature is available for use with SQL Server 7.0 and SQL Server 2000. When searching for data using a nonclustered index, the index is searched for a particular value. When that value is found, the index points to the disk address. The traditional approach would be to immediately issue an I/O for that row, given the disk address. The result is one synchronous I/O per row and, at most, one disk at a time working to evaluate the query. This does not take advantage of striped disk sets. The prefetch feature takes a different approach. It continues looking for more record pointers in the nonclustered index. When it has collected a number of them, it provides the storage engine with prefetch hints. These hints tell the storage engine that the query processor will need these particular records soon. The storage engine can now issue several I/Os simultaneously, taking advantage of striped disk sets to execute multiple operations simultaneously. For example, if the engine is scanning a nonclustered index to determine which rows qualify but will eventually need to visit the data page as well to access columns that are not in the index, it may decide to submit asynchronous page read requests for a group of qualifying rows. The prefetch data pages are then revisited later to avoid waiting for each individual page read to complete in a serial fashion. This data access path requires that a lock be held between the prefetch request and the row lookup to stabilize the row on the page so it is not to be moved by a page split or clustered key update. For our example, the isolation level of the query is escalated to REPEATABLE READ, overriding the transaction isolation level. With SQL Server 7.0 and SQL Server 2000, portions of a transaction can execute at a different transaction isolation level than the entire transaction itself. This is implemented as lock classes. Lock classes are used to control lock lifetime when portions of a transaction need to execute at a stricter isolation level than the underlying transaction. Unfortunately, in SQL Server 7.0 and SQL Server 2000, the lock class is created at the topmost operator of the query and hence released only at the end of the query. Currently there is no support to release the lock (lock class) after the row has been discarded or fetched by the filter or join operator. This is because isolation level can be set at the query level via a lock class, but no lower. Because of this, locks acquired during the query will not be released until the query completes. If prefetch is occurring you may see a single SPID that holds hundreds of Shared KEY or PAG locks even though the connection’s isolation level is READ COMMITTED. Isolation level can be determined from DBCC PSS output. For details about this behavior see “SOX001109700040 INF: Queries with PREFETCH in the plan hold lock until the end of transaction”. Other Locking Mechanism Lock manager does not manage latches and spinlocks. Latches Latches are internal mechanisms used to protect pages while doing operations such as placing a row physically on a page, compressing space on a page, or retrieving rows from a page. Latches can roughly be divided into I/O latches and non-I/O latches. If you see a high number of non-I/O related latches, SQL Server is usually doing a large number of hash or sort operations in tempdb. You can monitor latch activities via DBCC SQLPERF(‘WAITSTATS’) command. Spinlock A spinlock is an internal data structure that is used to protect vital information that is shared within SQL Server. On a multi-processor machine, when SQL Server tries to access a particular resource protected by a spinlock, it must first acquire the spinlock. If it fails, it executes a loop that will check to see if the lock is available and if not, decrements a counter. If the counter reaches zero, it yields the processor to another thread and goes into a “sleep” (wait) state for a pre-determined amount of time. When it wakes, hopefully, the lock is free and available. If not, the loop starts again and it is terminated only when the lock is acquired. The reason for implementing a spinlock is that it is probably less costly to “spin” for a short time rather than yielding the processor. Yielding the processor will force an expensive context switch where:  The old thread’s state must be saved  The new thread’s state must be reloaded  The data stored in the L1 and L2 cache are useless to the processor On a single-processor computer, the loop is not useful because no other thread can be running and thus, no one can release the spinlock for the currently executing thread to acquire. In this situation, the thread yields the processor immediately. Lesson 2: Concepts – Batch and Transaction This lesson outlines some of the common causes that contribute to the perception of a slow server. What You Will Learn After completing this lesson, you will be able to:  Review batch processing and error checking.  Review explicit, implicit and autocommit transactions and transaction nesting level.  Discuss how commit and rollback transaction done in stored procedure and trigger affects transaction nesting level.  Discuss various transaction isolation level and their impact on locking.  Discuss the difference between aborting a statement, a transaction, and a batch.  Describe how @@error, @@transcount, and @@rowcount can be used for error checking and handling. Recommended Reading  Charter 12 “Transactions and Triggers”, Inside SQL Server 2000 by Kalen Delaney Batch Definition SQL Profiler Statements and Batches To help further your understanding of what is a batch and what is a statement, you can use SQL Profiler to study the definition of batch and statement.  Try This: Using SQL Profiler to Analyze Batch 1. Log on to a server with Query Analyzer 2. Startup the SQL Profiler against the same server 3. Start a trace using the “StandardSQLProfiler” template 4. Execute the following using Query Analyzer: SELECT @@VERSION SELECT @@SPID The ‘SQL:BatchCompleted’ event is captured by the trace. It shows both the statements as a single batch. 5. Now execute the following using Query Analyzer {call sp_who()} What shows up? The ‘RPC:Completed’ with the sp_who information. RPC is simply another entry point to the SQL Server to call stored procedures with native data types. This allows one to avoid parsing. The ‘RPC:Completed’ event should be considered the same as a batch for the purposes of this discussion. Stop the current trace and start a new trace using the “SQLProfilerTSQL_SPs” template. Issue the same command as outlines in step 5 above. Looking at the output, not only can you see the batch markers but each statement as executed within the batch. Autocommit, Explicit, and Implicit Transaction Autocommit Transaction Mode (Default) Autocommit mode is the default transaction management mode of SQL Server. Every Transact-SQL statement, whether it is a standalone statement or part of a batch, is committed or rolled back when it completes. If a statement completes successfully, it is committed; if it encounters any error, it is rolled back. A SQL Server connection operates in autocommit mode whenever this default mode has not been overridden by either explicit or implicit transactions. Autocommit mode is also the default mode for ADO, OLE DB, ODBC, and DB-Library. A SQL Server connection operates in autocommit mode until a BEGIN TRANSACTION statement starts an explicit transaction, or implicit transaction mode is set on. When the explicit transaction is committed or rolled back, or when implicit transaction mode is turned off, SQL Server returns to autocommit mode. Explicit Transaction Mode An explicit transaction is a transaction that starts with a BEGIN TRANSACTION statement. An explicit transaction can contain one or more statements and must be terminated by either a COMMIT TRANSACTION or a ROLLBACK TRANSACTION statement. Implicit Transaction Mode SQL Server can automatically or, more precisely, implicitly start a transaction for you if a SET IMPLICIT_TRANSACTIONS ON statement is run or if the implicit transaction option is turned on globally by running sp_configure ‘user options’ 2. (Actually, the bit mask 0x2 must be turned on for the user option so you might have to perform an ‘OR’ operation with the existing user option value.) See SQL Server 2000 Books Online on how to turn on implicit transaction under ODBC and OLE DB (acdata.chm::/ac_8_md_06_2g6r.htm). Transaction Nesting Explicit transactions can be nested. Committing inner transactions is ignored by SQL Server other than to decrements @@TRANCOUNT. The transaction is either committed or rolled back based on the action taken at the end of the outermost transaction. If the outer transaction is committed, the inner nested transactions are also committed. If the outer transaction is rolled back, then all inner transactions are also rolled back, regardless of whether the inner transactions were individually committed. Each call to COMMIT TRANSACTION applies to the last executed BEGIN TRANSACTION. If the BEGIN TRANSACTION statements are nested, then a COMMIT statement applies only to the last nested transaction, which is the innermost transaction. Even if a COMMIT TRANSACTION transaction_name statement within a nested transaction refers to the transaction name of the outer transaction, the commit applies only to the innermost transaction. If a ROLLBACK TRANSACTION statement without a transaction_name parameter is executed at any level of a set of nested transaction, it rolls back all the nested transactions, including the outermost transaction. The @@TRANCOUNT function records the current transaction nesting level. Each BEGIN TRANSACTION statement increments @@TRANCOUNT by one. Each COMMIT TRANSACTION statement decrements @@TRANCOUNT by one. A ROLLBACK TRANSACTION statement that does not have a transaction name rolls back all nested transactions and decrements @@TRANCOUNT to 0. A ROLLBACK TRANSACTION that uses the transaction name of the outermost transaction in a set of nested transactions rolls back all the nested transactions and decrements @@TRANCOUNT to 0. When you are unsure if you are already in a transaction, SELECT @@TRANCOUNT to determine whether it is 1 or more. If @@TRANCOUNT is 0 you are not in a transaction. You can also find the transaction nesting level by checking the sysprocess.open_tran column. See SQL Server 2000 Books Online topic “Nesting Transactions” (acdata.chm::/ac_8_md_06_66nq.htm) for more information. Statement, Transaction, and Batch Abort One batch can have many statements and one transaction can have multiple statements, also. One transaction can span multiple batches and one batch can have multiple transactions. Statement Abort Currently executing statement is aborted. This can be a bit confusing when you start talking about statements in a trigger or stored procedure. Let us look closely at the following trigger: CREATE TRIGGER TRG8134 ON TBL8134 AFTER INSERT AS BEGIN SELECT 1/0 SELECT 'Next command in trigger' END To fire the INSERT trigger, the batch could be as simple as ‘INSERT INTO TBL8134 VALUES(1)’. However, the trigger contains two statements that must be executed as part of the batch to satisfy the clients insert request. When the ‘SELECT 1/0’ causes the divide by zero error, a statement abort is issued for the ‘SELECT 1/0’ statement. Batch and Transaction Abort On SQL Server 2000 (and SQL Server 7.0) whenever a non-informational error is encountered in a trigger, the statement abort is promoted to a batch and transactional abort. Thus, in the example the statement abort for ‘select 1/0’ promotion results in an entire batch abort. No further statements in the trigger or batch will be executed and a rollback is issued. On SQL Server 6.5, the statement aborts immediately and results in a transaction abort. However, the rest of the statements within the trigger are executed. This trigger could return ‘Next command in trigger’ as a result set. Once the trigger completes the batch abort promotion takes effect. Conversely, submitting a similar set of statements in a standalone batch can result in different behavior. SELECT 1/0 SELECT 'Next command in batch' Not considering the set option possibilities, a divide by zero error generally results in a statement abort. Since it is not in a trigger, the promotion to a batch abort is avoided and subsequent SELECT statement can execute. The programmer should add an “if @@ERROR” check immediately after the ‘select 1/0’ to T-SQL execution to control the flow correctly. Aborting and Set Options ARITHABORT If SET ARITHABORT is ON, these error conditions cause the query or batch to terminate. If the errors occur in a transaction, the transaction is rolled back. If SET ARITHABORT is OFF and one of these errors occurs, a warning message is displayed, and NULL is assigned to the result of the arithmetic operation. When an INSERT, DELETE, or UPDATE statement encounters an arithmetic error (overflow, divide-by-zero, or a domain error) during expression evaluation when SET ARITHABORT is OFF, SQL Server inserts or updates a NULL value. If the target column is not nullable, the insert or update action fails and the user receives an error. XACT_ABORT When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back. When OFF, only the Transact-SQL statement that raised the error is rolled back and the transaction continues processing. Compile errors, such as syntax errors, are not affected by SET XACT_ABORT. For example: CREATE TABLE t1 (a int PRIMARY KEY) CREATE TABLE t2 (a int REFERENCES t1(a)) GO INSERT INTO t1 VALUES (1) INSERT INTO t1 VALUES (3) INSERT INTO t1 VALUES (4) INSERT INTO t1 VALUES (6) GO SET XACT_ABORT OFF GO BEGIN TRAN INSERT INTO t2 VALUES (1) INSERT INTO t2 VALUES (2) /* Foreign key error */ INSERT INTO t2 VALUES (3) COMMIT TRAN SELECT 'Continue running batch 1...' GO SET XACT_ABORT ON GO BEGIN TRAN INSERT INTO t2 VALUES (4) INSERT INTO t2 VALUES (5) /* Foreign key error */ INSERT INTO t2 VALUES (6) COMMIT TRAN SELECT 'Continue running batch 2...' GO /* Select shows only keys 1 and 3 added. Key 2 insert failed and was rolled back, but XACT_ABORT was OFF and rest of transaction succeeded. Key 5 insert error with XACT_ABORT ON caused all of the second transaction to roll back. Also note that 'Continue running batch 2...' is not Returned to indicate that the batch is aborted. */ SELECT * FROM t2 GO DROP TABLE t2 DROP TABLE t1 GO Compile and Run-time Errors Compile Errors Compile errors are encountered during syntax checks, security checks, and other general operations to prepare the batch for execution. These errors can prevent the optimization of the query and thus lead to immediate abort. The statement is not run and the batch is aborted. The transaction state is generally left untouched. For example, assume there are four statements in a particular batch. If the third statement has a syntax error, none of the statements in the batch is executed. Optimization Errors Optimization errors would include rare situations where the statement encounters a problem when attempting to build an optimal execution plan. Example: “too many tables referenced in the query” error is reported because a “work table” was added to the plan. Runtime Errors Runtime errors are those that are encountered during the execution of the query. Consider the following batch: SELECT * FROM pubs.dbo.titles UPDATE pubs.dbo.authors SET au_lname = au_lname SELECT * FROM foo UPDATE pubs.dbo.authors SET au_lname = au_lname If you run the above statements in a batch, the first two statements will be executed, the third statement will fail because table foo does not exist, and the batch will terminate. Deferred Name Resolution is the feature that allows this batch to start executing before resolving the object foo. This feature allows SQL Server to delay object resolution and place a “placeholder” in the query’s execution. The object referenced by the placeholder is resolved until the query is executed. In our example, the execution of the statement “SELECT * FROM foo” will trigger another compile process to resolve the name again. This time, error message 208 is returned. Error: 208, Level 16, State 1, Line 1 Invalid object name 'foo'. Message 208 can be encountered as a runtime or compile error depending on whether the Deferred Name Resolution feature is available. In SQL Server 6.5 this would be considered a compile error and on SQL Server 2000 (and SQL Server7.0) as a runtime error due to Deferred Name Resolution. In the following example, if a trigger referenced authors2, the error is detected as SQL Server attempts to execute the trigger. However, under SQL Server 6.5 the create trigger statement fails because authors2 does not exist at compile time. When errors are encountered in a trigger, generally, the statement, batch, and transaction are aborted. You should be able to observe this by running the following script in pubs database: Create table tblTest(iID int) go create trigger trgInsert on tblTest for INSERT as begin select * from authors select * from authors2 select * from titles end go begin tran select 'Before' insert into tblTest values(1) select 'After' go select @@TRANCOUNT go When run in a batch, the statement and the batch are aborted but the transaction remains active. The follow script illustrates this: begin tran select 'Before' select * from authors2 select 'After' go select @@TRANCOUNT go One other factor in a compile versus runtime error is implicit data type conversions. If you were to run the following statements on SQL Server 6.5 and SQL Server 2000 (and SQL Server 7.0): create table tblData(dtData datetime) go select 1 insert into tblData values(12/13/99) go On SQL Server 6.5, you get an error before execution of the batch begins so no statements are executed and the batch is aborted. Error: 206, Level 16, State 2, Line 2 Operand type clash: int is incompatible with datetime On SQL Server 2000, you get the default value (1900-01-01 00:00:00.000) inserted into the table. SQL Server 2000 implicit data type conversion treats this as integer division. The integer division of 12/13/99 is 0, so the default date and time value is inserted, no error returned. To correct the problem on either version is to wrap the date string with quotes. See Bug #56118 (sqlbug_70) for more details about this situation. Another example of a runtime error is a 605 message. Error: 605 Attempt to fetch logical page %S_PGID in database '%.*ls' belongs to object '%.*ls', not to object '%.*ls'. A 605 error is always a runtime error. However, depending on the transaction isolation level, (e.g. using the NOLOCK lock hint), established by the SPID the handling of the error can vary. Specifically, a 605 error is considered an ACCESS error. Errors associated with buffer and page access are found in the 600 series of errors. When the error is encountered, the isolation level of the SPID is examined to determine proper handling based on information or fatal error level. Transaction Error Checking Not all errors cause transactions to automatically rollback. Although it is difficult to determine exactly which errors will rollback transactions and which errors will not, the main idea here is that programmers must perform error checking and handle errors appropriately. Error Handling Raiserror Details Raiserror seems to be a source of confusion but is really rather simple. Raiserror with severity levels of 20 or higher will terminate the connection. Of course, when the connection is terminated a full rollback of any open transaction will immediately be instantiated by the SQL Server (except distributed transaction with DTC involved). Severity levels lower than 20 will simply result in the error message being returned to the client. They do not affect the transaction scope of the connection. Consider the following batch: use pubs begin tran update authors set au_lname = 'smith' raiserror ('This is bad', 19, 1) with log select @@trancount With severity set at 19, the 'select @@trancount' will be executed after the raiserror statement and will return a value of 1. If severity is changed to 20, then the select statement will not run and the connection is broken. Important Error handling must occur not only in T-SQL batches and stored procedures, but also in application program code. Transactions and Triggers (1 of 2) Basic behavior assumes the implicit transactions setting is set to OFF. This behavior makes it possible to identify business logic errors in a trigger, raise an error, rollback the action, and add an audit table entry. Logically, the insert to the audit table cannot take place before the ROLLBACK action and you would not want to build in the audit table insert into every applications error handler that violated the business rule of the trigger. For more information, see also… SQL Server 2000 Books Online topic “Rollbacks in stored procedure and triggers“ (acdata.chm::/ac_8_md_06_4qcz.htm) IMPLICIT_TRANSACTIONS ON Behavior The behavior of firing other triggers on the same table can be tricky. Say you added a trigger that checks the CODE field. Read only versions of the rows contain the code ‘RO’ and read/write versions use ‘RW.’ Whenever someone tries to delete a row with a code ‘RO’ the trigger issues the rollback and logs an audit table entry. However, you also have a second trigger that is responsible for cascading delete operations. One client could issue the delete without implicit transactions on and only the current trigger would execute and then terminate the batch. However, a second client with implicit transactions on could issue the same delete and the secondary trigger would fire. You end up with a situation in which the cascading delete operations can take place (are committed) but the initial row remains in the table because of the rollback operation. None of the delete operations should be allowed but because the transaction scope was restarted because of the implicit transactions setting, they did. Transactions and Triggers (2 of 2) It is extremely difficult to determine the execution state of a trigger when using explicit rollback statements in combination with implicit transactions. The RETURN statement is not allowed to return a value. The only way I have found to set the @@ERROR is using a ‘raiserror’ as the last execution statement in the last trigger to execute. If you modify the example, this following RAISERROR statement will set @@ERROR to 50000: CREATE TRIGGER trgTest on tblTest for INSERT AS BEGIN ROLLBACK INSERT INTO tblAudit VALUES (1) RAISERROR('This is bad', 14,1) END However, this value does not carry over to a secondary trigger for the same table. If you raise an error at the end of the first trigger and then look at @@ERROR in the secondary trigger the @@ERROR remains 0. Carrying Forward an Active/Open Transaction It is possible to exit from a trigger and carry forward an open transaction by issuing a BEGIN TRAN or by setting implicit transaction on and doing INSERT, UPDATE, or DELETE. Warning It is never recommended that a trigger call BEGIN TRANSACTION. By doing this you increment the transaction count. Invalid code logic, not calling commit transaction, can lead to a situation where the transaction count remains elevated upon exit of the trigger. Transaction Count The behavior is better explained by understanding how the server works. It does not matter whether you are in a transaction, when a modification takes place the transaction count is incremented. So, in the simplest form, during the processing of an insert the transaction count is 1. On completion of the insert, the server will commit (and thus decrement the transaction count). If the commit identifies the transaction count has returned to 0, the actual commit processing is completed. Issuing a commit when the transaction count is greater than 1 simply decrements the nested transaction counter. Thus, when we enter a trigger, the transaction count is 1. At the completion of the trigger, the transaction count will be 0 due to the commit issued at the end of the modification statement (insert). In our example, if the connection was already in a transaction and called the second INSERT, since implicit transaction is ON, the transaction count in the trigger will be 2 as long as the ROLLBACK is not executed. At the end of the insert, the commit is again issued to decrement the transaction reference count to 1. However, the value does not return to 0 so the transaction remains open/active. Subsequent triggers are only fired if the transaction count at the end of the trigger remains greater than or equal to 1. The key to continuation of secondary triggers and the batch is the transaction count at the end of a trigger execution. If the trigger that performs a rollback has done an explicit begin transaction or uses implicit transactions, subsequent triggers and the batch will continue. If the transaction count is not 1 or greater, subsequent triggers and the batch will not execute. Warning Forcing the transaction count after issuing a rollback is dangerous because you can easily loose track of your transaction nesting level. When performing an explicit rollback in a trigger, you should immediately issue a return statement to maintain consistent behavior between a connection with and without implicit transaction settings. This will force the trigger(s) and batch to terminate immediately. One of the methods of dealing with this issue is to run ‘SET IMPLICIT_TRANSACTIONS OFF’ as the first statement of any trigger. Other methods may entails checking @@TRANCOUNT at the end of the trigger and continue to COMMIT the transaction as long as @@TRANCOUNT is greater than 1. Examples The following examples are based on this table: create table tbl50000Insert (iID int NOT NULL) go Note If more than one trigger is used, to guarantee the trigger firing sequence, the sp_settriggerorder command should be used. This command is omitted in these examples to simplify the complexity of the statements. First Example In the first example, the second trigger was never fired and the batch, starting with the insert statement, was aborted. Thus, the print statement was never issued. print('Trigger issues rollback - cancels batch') go create trigger trg50000Insert on tbl50000Insert for INSERT as begin select 'Inserted', * from inserted rollback tran select 'End of trigger', @@TRANCOUNT as 'TRANCOUNT' end go create trigger trg50000Insert2 on tbl50000Insert for INSERT as begin select 'In Trigger2' select 'Trigger 2 Inserted', * from inserted end go insert into tbl50000Insert values(1) print('---------------------- In same batch') select * from tbl50000Insert go -- Cleanup drop trigger trg50000Insert drop trigger trg50000Insert2 go delete from tbl50000Insert Second Example The next example shows that since a new transaction is started, the second trigger will be fired and the print statement in the batch will be executed. Note that the insert is rolled back. print('Trigger issues rollback - increases tran count to continue batch') go create trigger trg50000Insert on tbl50000Insert for INSERT as begin select 'Inserted', * from inserted rollback tran begin tran end go create trigger trg50000Insert2 on tbl50000Insert for INSERT as begin select 'In Trigger2' select 'Trigger 2 Inserted', * from inserted end go insert into tbl50000Insert values(2) print('---------------------- In same batch') select * from tbl50000Insert go -- Cleanup drop trigger trg50000Insert drop trigger trg50000Insert2 go delete from tbl50000Insert Third Example In the third example, the raiserror statement is used to set the @@ERROR value and the BEGIN TRAN statement is used in the trigger to allow the batch to continue to run. print('Trigger issues rollback - uses raiserror to set @@ERROR') go create trigger trg50000Insert on tbl50000Insert for INSERT as begin select 'Inserted', * from inserted rollback tran begin tran -- Increase @@trancount to allow -- batch to continue select @@trancount as ‘Trancount’ raiserror('This is from the trigger', 14,1) end go insert into tbl50000Insert values(3) select @@ERROR as 'ERROR', @@TRANCOUNT as 'Trancount' go -- Cleanup drop trigger trg50000Insert go delete from tbl50000Insert Fourth Example For the fourth example, a second trigger is added to illustrate the fact that @@ERROR value set in the first trigger will not be seen in the second trigger nor will it show up in the batch after the second trigger is fired. print('Trigger issues rollback - uses raiserror to set @@ERROR, not seen in second trigger and cleared in batch') go create trigger trg50000Insert on tbl50000Insert for INSERT as begin select 'Inserted', * from inserted rollback begin tran -- Increase @@trancount to -- allow batch to continue select @@TRANCOUNT as 'Trancount' raiserror('This is from the trigger', 14,1) end go create trigger trg50000Insert2 on tbl50000Insert for INSERT as begin select @@ERROR as 'ERROR', @@TRANCOUNT as 'Trancount' end go insert into tbl50000Insert values(4) select @@ERROR as 'ERROR', @@TRANCOUNT as 'Trancount' go -- Cleanup drop trigger trg50000Insert drop trigger trg50000Insert2 go delete from tbl50000Insert Lesson 3: Concepts – Locks and Applications This lesson outlines some of the common causes that contribute to the perception of a slow server. What You Will Learn After completing this lesson, you will be able to:  Explain how lock hints are used and their impact.  Discuss the effect on locking when an application uses Microsoft Transaction Server.  Identify the different kinds of deadlocks including distributed deadlock. Recommended Reading  Charter 14 “Locking”, Inside SQL Server 2000 by Kalen Delaney  Charter 16 “Query Tuning”, Inside SQL Server 2000 by Kalen Delaney Q239753 – Deadlock Situation Not Detected by SQL Server Q288752 – Blocked SPID Not Participating in Deadlock May Incorrectly be Chosen as victim Locking Hints UPDLOCK If update locks are used instead of shared locks while reading a table, the locks are held until the end of the statement or transaction. UPDLOCK has the advantage of allowing you to read data (without blocking other readers) and update it later with the assurance that the data has not changed since you last read it. READPAST READPAST is an optimizer hint for use with SELECT statements. When this hint is used, SQL Server will read past locked rows. For example, assume table T1 contains a single integer column with the values of 1, 2, 3, 4, and 5. If transaction A changes the value of 3 to 8 but has not yet committed, a SELECT * FROM T1 (READPAST) yields values 1, 2, 4, 5. Tip READPAST only applies to transactions operating at READ COMMITTED isolation and only reads past row-level locks. This lock hint can be used to implement a work queue on a SQL Server table. For example, assume there are many external work requests being thrown into a table and they should be serviced in approximate insertion order but they do not have to be completely FIFO. If you have 4 worker threads consuming work items from the queue they could each pick up a record using read past locking and then delete the entry from the queue and commit when they're done. If they fail, they could rollback, leaving the entry on the queue for the next worker thread to pick up. Caution The READPAST hint is not compatible with HOLDLOCK.  Try This: Using Locking Hints 1. Open a Query Window and connect to the pubs database. 2. Execute the following statements (--Conn 1 is optional to help you keep track of each connection): BEGIN TRANSACTION -- Conn 1 UPDATE titles SET price = price * 0.9 WHERE title_id = 'BU1032' 3. Open a second connection and execute the following statements: SELECT @@lock_timeout -- Conn 2 GO SELECT * FROM titles SELECT * FROM authors 4. Open a third connection and execute the following statements: SET LOCK_TIMEOUT 0 -- Conn 3 SELECT * FROM titles SELECT * FROM authors 5. Open a fourth connection and execute the following statement: SELECT * FROM titles (READPAST) -- Conn 4 WHERE title_ID < 'C' SELECT * FROM authors How many records were returned? 3 6. Open a fifth connection and execute the following statement: SELECT * FROM titles (NOLOCK) -- Conn 5 WHERE title_ID 0 the lock manager also checks for deadlocks every time a SPID gets blocked. So a single deadlock will trigger 20 seconds of more immediate deadlock detection, but if no additional deadlocks occur in that 20 seconds, the lock manager no longer checks for deadlocks at each block and detection again only happens every 5 seconds. Although normally not needed, you may use trace flag -T1205 to trace the deadlock detection process. Note Please note the distinction between application lock and other locks’ deadlock detection. For application lock, we do not rollback the transaction of the deadlock victim but simply return a -3 to sp_getapplock, which the application needs to handle itself. Deadlock Resolution How is a deadlock resolved? SQL Server picks one of the connections as a deadlock victim. The victim is chosen based on either which is the least expensive transaction (calculated using the number and size of the log records) to roll back or in which process “SET DEADLOCK_PRIORITY LOW” is specified. The victim’s transaction is rolled back, held locks are released, and SQL Server sends error 1205 to the victim’s client application to notify it that it was chosen as a victim. The other process can then obtain access to the resource it was waiting on and continue. Error 1205: Your transaction (process ID #%d) was deadlocked with another process and has been chosen as the deadlock victim. Rerun your transaction. Symptoms of deadlocking Error 1205 usually is not written to the SQL Server errorlog. Unfortunately, you cannot use sp_altermessage to cause 1205 to be written to the errorlog. If the client application does not capture and display error 1205, some of the symptoms of deadlock occurring are:  Clients complain of mysteriously canceled queries when using certain features of an application.  May be accompanied by excessive blocking. Lock contention increases the chances that a deadlock will occur. Triggers and Deadlock Triggers promote the deadlock priority of the SPID for the life of the trigger execution when the DEADLOCK PRIORITY is not set to low. When a statement in a trigger causes a deadlock to occur, the SPID executing the trigger is given preferential treatment and will not become the victim. Warning Bug 235794 is filed against SQL Server 2000 where a blocked SPID that is not a participant of a deadlock may incorrectly be chosen as a deadlock victim if the SPID is blocked by one of the deadlock participants and the SPID has the least amount of transaction logging. See KB article Q288752: “Blocked Spid Not Participating in Deadlock May Incorrectly be Chosen as victim” for more information. Distributed Deadlock – Scenario 1 Distributed Deadlocks The term distributed deadlock is ambiguous. There are many types of distributed deadlocks. Scenario 1 Client application opens connection A, begins a transaction, acquires some locks, opens connection B, connection B gets blocked by A but the application is designed to not commit A’s transaction until B completes. Note SQL Server has no way of knowing that connection A is somehow dependent on B – they are two distinct connections with two distinct transactions. This situation is discussed in scenario #4 in “Q224453 INF: Understanding and Resolving SQL Server 7.0 Blocking Problems”. Distributed Deadlock – Scenario 2 Scenario 2 Distributed deadlock involving bound connections. Two connections can be bound into a single transaction context with sp_getbindtoken/sp_bindsession or via DTC. Spid 60 enlists in a transaction with spid 61. A third spid 62 is blocked by spid 60, but spid 61 is blocked by spid 62. Because they are doing work in the same transaction, spid 60 cannot commit until spid 61 finishes his work, but spid 61 is blocked by 62 who is blocked by 60. This scenario is described in article “Q239753 - Deadlock Situation Not Detected by SQL Server.” Note SQL Server 6.5 and 7.0 do not detect this deadlock. The SQL Server 2000 deadlock detection algorithm has been enhanced to detect this type of distributed deadlock. The diagram in the slide illustrates this situation. Resources locked by a spid are below that spid (in a box). Arrows indicate blocking and are drawn from the blocked spid to the resource that the spid requires. A circle represents a transaction; spids in the same transaction are shown in the same circle. Distributed Deadlock – Scenario 3 Scenario 3 Distributed deadlock involving linked servers or server-to-server RPC. Spid 60 on Server 1 executes a stored procedure on Server 2 via linked server. This stored procedure does a loopback linked server query against a table on Server 1, and this connection is blocked by a lock held by Spid 60. Note No version of SQL Server is currently designed to detect this distributed deadlock. Lesson 4: Information Collection and Analysis This lesson outlines some of the common causes that contribute to the perception of a slow server. What You Will Learn After completing this lesson, you will be able to:  Identify specific information needed for troubleshooting issues.  Locate and collect information needed for troubleshooting issues.  Analyze output of DBCC Inputbuffer, DBCC PSS, and DBCC Page commands.  Review information collected from master.dbo.sysprocesses table.  Review information collected from master.dbo.syslockinfo table.  Review output of sp_who, sp_who2, sp_lock.  Analyze Profiler log for query usage pattern.  Review output of trace flags to help troubleshoot deadlocks. Recommended Reading Q244455 - INF: Definition of Sysprocesses Waittype and Lastwaittype Fields Q244456 - INF: Description of DBCC PSS Command for SQL Server 7.0 Q271509 - INF: How to Monitor SQL Server 2000 Blocking Q251004 - How to Monitor SQL Server 7.0 Blocking Q224453 - Understanding and Resolving SQL Server 7.0 Blocking Problem Q282749 – BUG: Deadlock information reported with SQL Server 2000 Profiler Locking and Blocking  Try This: Examine Blocked Processes 1. Open a Query Window and connect to the pubs database. Execute the following statements: BEGIN TRAN -- connection 1 UPDATE titles SET price = price + 1 2. Open another connection and execute the following statement: SELECT * FROM titles-- connection 2 3. Open a third connection and execute sp_who; note the process id (spid) of the blocked process. (Connection 3) 4. In the same connection, execute the following: SELECT spid, cmd, waittype FROM master..sysprocesses WHERE waittype 0 -- connection 3 5. Do not close any of the connections! What was the wait type of the blocked process?  Try This: Look at locks held Assumes all your connections are still open from the previous exercise. • Execute sp_lock -- Connection 3 What locks is the process from the previous example holding? Make sure you run ROLLBACK TRAN in Connection 1 to clean up your transaction. Collecting Information See Module 2 for more about how to gather this information using various tools. Recognizing Blocking Problems How to Recognize Blocking Problems  Users complain about poor performance at a certain time of day, or after a certain number of users connect.  SELECT * FROM sysprocesses or sp_who2 shows non-zero values in the blocked or BlkBy column.  More severe blocking incidents will have long blocking chains or large sysprocesses.waittime values for blocked spids.  Possibl
SQLServer考试题及答案 选择题: 1、在MS SQL Server,用来显示数据库信息的系统存储过程是( ) A sp_ dbhelp B sp_ db C sp_ help D sp_ helpdb 2、SQL语言,删除一个表的命令是( ) A DELETE B DROP C CLEAR D REMORE 3、关系数据库,主键是(__) A、为标识表唯一的实体 B、创建唯一的索引,允许空值 C、只允许以表第一字段建立 D、允许有多个主键的 4、在Transact-SQL语法,SELECT语句的完整语法较复杂,但至少包括的部分(1___),使用关键字(2___)可以把重复行屏蔽,将多个查询结果返回一个结果集合的运算符是(3___),如果在SELECT语句使用聚合函数时,一定在后面使用(4___)。 ⑴ A、SELECT,INTO B、SELECT,FROM C、SELECT,GROUP D、仅SELECT ⑵ A、DISTINCT B、UNION C、ALL D、TOP ⑶ A、JOIN B、UNION C、INTO D、LIKE ⑷ A、GROUP BY B、COMPUTE BY C、HAVING D、COMPUTE 5、语句DBCC SHRINKDATABASE (Sample, 25)的25表示的意思是 A、25M B、剩余占整个空间的25% C、已用空间占整个空间的25% D、以上都不对 6、你是一个保险公司的数据库开发人员,公司的保单信息存储在SQL Server 2000数据库,你使用以下脚本建立了一个名为Policy的表: CREATE TABLE Policy (PolicyNumber int NOT NULL DEFAULT (0), InsuredLastName char (30) NOT NULL, InsuredFirstName char (20) NOT NULL, InsuredBirthDate datetime NOT NULL, PolicyDate datetime NOT NULL, FaceAmount money NOT NULL, CONSTRAINT PK_Policy PRIMARY KEY (PolicyNumber) ) 每次公司销售出一份保单,Policy表就增加一条记录,并赋予其一个新的保单号,你将怎么做? a.建立一个INSTEAD OF INSERT触发器来产生一个新的保单号,并将这个保单号插入数据表。 b.建立一个INSTEAD OF UPDATE触发器来产生一个新的保单号,并将这个保单号插入数据表。 c.建立一个AFTER UPDATE触发器来产生一个新的保单号,并将这个保单号插入数据表。 d.用AFTER UPDATE触发器替代DEFAULT约束条件产生一个新的保单号,并将这个保单号插入数据表
SQL sever 2008 Rar! ?s X<t ? ? ? ?祕BwL0 17240671-1.sql ?<9--2018年3月9日 --1.查询course表的所有信息(所有行所有列) USE Xk GO SELECT * FROM Course --有哪些种类的选修课?学分是多少 USE XK GO SELECT Kind,Credit FROM Crouse GO 修改列名字 SELECT '课程种类'=Kind,'学分'=Credit FROM Course GO --查询Course表的前10行 SELECT TOP 10 * FROM Course GO --查询Course表的前10%行 USE Xk GO SELECT TOP 10 PERCENT * FROM Course GO ㄚt 扚 ? ? h2=C蚅0! 17240671-13.3实训.sql [?灜? sql ?`?-2018.4.18 USE master GO --单元五 创建于管理数据库 --创建数据库Sale CREATE DATABASE sale ON PRIMARY (NAME=sale, FILENAME='C:\\sale.mdf', SIZE=4MB, MAXSIZE=20MB, FILEGROWTH=1MB ) LOG ON (NAME=sale_log, FILENAME='C:\\sale_log.ldf', SIZE=10MB, MAXSIZE=20MB, FILEGROWTH=1MB) GO --向数据库增加文件组UserGroup ALTER DATABASE sale ADD FILEGROUP UserGroup GO ALTER DATABASE sale ADD FILE (NAME='sale_data3', FILENAME='D:\\sale_data3.ndf', SIZE=5MB, MAXSIZE=10MB, FILEGROWTH=1MB ) TO FILEGROUP UserGroup GO sp_help sale GO USE master GO -- 单元六 创建于管理数据表 --创建客户表结构Customer CREATE TABLE Customer (CusNO nvarchar(3) NOT NULL, CusName nvarchar(10), Address nvarchar(20)NOT NULL, Tel nvarchar(20) NOT NULL) GO --创建场品表结构Product CREATE TABLE Product (ProNO nvarchar(5) NOT NULL, ProName nvarchar(20)NOT NULL, Price Decimal(8,2) NOT NULL, Stocks Decimal(6,0) NOT NULL) GO --创建入库表结构Proln CREATE TABLE Proln (InputDate DateTime NOT NULL, ProNo nvarchar(5) NOT NULL, Quantity Decimal(6,0) NOT NULL) GO --创建销售表结构Proout CREATE TABLE Proout (SaleDate DateTime NOT NULL, CusNo nvarchar(3) NOT NULL, ProNo nvarchar(5) NOT NULL, Quantity Decimal(6,0) NOT NULL, Amount Decimal(8,2)NOT NULL) GO --向已创建的表添加数据 INSERT Customer VALUES('001','杨婷','深圳','0755-22221111') INSERT Customer VALUES('002','陈萍','深圳','0755-22223333') INSERT Customer VALUES('003','李东','深圳','0755-22225555') INSERT Customer VALUES('004','叶合','广州','0755-22225555') INSERT Customer VALUES('005','谭新','广州','0755-22225555') Go INSERT Customer VALUES('0001','电视',3000.00,800) INSERT Customer VALUES('0002','空调',2000.00,500) INSERT Customer VALUES('0003','床',1000.00,300) INSERT Customer VALUES('0004','餐桌',1500.00,200) INSERT Customer VALUES('0005','音响',5000.00,600) INSERT Customer VALUES('0006','沙发',6000.00,100) Go INSERT Proln VALUES('2006-1-1','00001',10) INSERT Proln VALUES('2006-1-2','00002',5) INSERT Proln VALUES('2006-1-3','00001',5) INSERT Proln VALUES('2006-2-1','00003',10) INSERT Proln VALUES('2006-2-2','00001',10) INSERT Proln VALUES('2006-2-3','00003',20) INSERT Proln VALUES('2006-3-2','00001',10) INSERT Proln VALUES('2006-3-2','00004',30) INSERT Proln VALUES('2006-3-3','00003',20) Go INSERT ProOut VALUES('2006-1-1','001','00001',10) INSERT ProOut VALUES('2006-1-2','001','00002',5) INSERT ProOut VALUES('2006-1-3','002','00001',5) INSERT ProOut VALUES('2006-2-1','002','00003',10) INSERT ProOut VALUES('2006-2-2','001','00001',10) INSERT ProOut VALUES('2006-2-3','001','00003',20) INSERT ProOut VALUES('2006-3-2','003','00001',10) INSERT ProOut VALUES('2006-3-2','003','00004',30) INSERT ProOut VALUES('2006-3-3','002','00003',20) Go --单元七 实施数据完整性(约束) --使用ALTER TABLE 语句为已经创建的表添加主键约束、外键约束 --主键 ALTER TABLE Customer ADD CONSTRAINT PK_Customer PRIMARY KEY(CusNo) GO ALTER TABLE Product ADD CONSTRAINT PK_Product PRIMARY KEY(ProNo) GO --外键 ALTER TABLE Proout ADD CONSTRAINT FK_Proout_Product FOREIGN KEY(ProNo) REFERENCES Product(ProNo) GO ALTER TABLE Proout ADD CONSTRAINT FK_Proout_Customer FOREIGN KEY(CusNo) REFERENCES Customer(Customer) GO ALTER TABLE Proln ADD CONSTRAINT FK_Proln_Product FOREIGN KEY(ProNo) REFERENCES Product(ProNo) GO --约束客户表Customer的CosNo的列值长度为3,产品表Product 的ProNo 列值长度为5 ALTER TABLE Coustomer ADD CONSTRAINT CK_Customer_CusNo CHECK (CusNo like '[0-9][0-9][0-9]') GO ALTER TABLE Product ADD CONSTRAINT CK_Product_ProNo CHECK(ProNo like'[0-9][0-9][0-9][0-9][0-9]') GO --对产品表Product 的Stocks列、Price列、入库表Proln的Quanity列、销售表ProOut 的Quanity --列值进行约束,使其值大于0 ALTER TABLE Product ADD CONSTRAINT CK_Product_Stock CHECK(Stock>0) GO ALTER TABLE Product ADD CONSTRAINT CK_Product_Price CHECK(Price>0) GO ALTER TABLE Proln ADD CONSTRAINT CK_Proln_Quantity CHECK (Quantity>0) GO ALTER TABLE ProOut ADD CONSTRAINT CK_ProOut_Quantity CHECK(Quantity>0) GO --对销售表ProOut的SaleDate 列进行约束,当不输入值时,系统默认其值为系统当前日期 CREATE DEFAULT Today AS GETDATEA() GO /*ALTER TABLE ProOut ADD CONSTRAINT DF_ProOut_SaleDate DEFAULT('当前日期')FOR Date GO*/ --单元八 索引 --用户按照CusName查询客户信息,希望提高查询速度 CREATE UNIQUE INDEX IX_CusName ON Customer(CusName) GO --用户按照ProName查询产品信息,希望提高查询速度 CREATE UNIQUE INDEX IX_ProName ON Product(ProName) GO --用户按照SaleDate查询产品信息,希望提高查询速度 CREATE UNIQUE INDEX IX_SaleDate ON ProOut(SaleDate) GO --单元九 语言编程基础 --计算有多少种产品(假设为x),然后显示一条信息:共有X种产品 DECLARE @X int SET @X =(SELECT COUNT (*) FROM Product ) PRINT '共有'+convert (char(2),@x)+'种产品。' GO --编写计算n!(n=20)的程序,并显示结果。 DECLARE @X int,@product int SELECT @X=1,@product=1 WHILE @X<=20 BEGIN SELECT @X=@X+1 SELECT @product=@product*@X END SELECT '1*2*3*......*20的积'=@product GO --单元十 创建于管理视图 --创建视图V_Sale1,并显示销售日期、客户编号、客户姓名、产品编号、产品名称、单价 --销售数量、销售金额 CREATE VIEW V_Sale1 AS SELECT SaleDate,Customer.CusNO,CusName,Product.ProNO,ProName,Price,Proout.Quantity, SM=(Price *Proout.Quantity) FROM Customer ,Product,Proln,Proout WHERE Customer.CusNO=Proout.CusNo AND Product.ProNO=Proln.ProNo AND Product.ProNO=Proout.ProNo AND Proout.Quantity=Proln.Quantity GO --创建视图V-Sale2,统计每种产品的销售数量和销售金额。统计结果包括产品编号、 --产品名称、单价、销售数量和销售金额 CREATE VIEW V_Sale2 AS SELECT Product.ProNO ,ProName,Price,Proout.Quantity ,SM=(Price *Proout.Quantity) FROM Product ,Proout ,Proln GROUP BY ProName GO --创建视图V_Sale3,统计销售金额在10万以下的产品信息。 CREATE VIEW V_Sale3 AS SELECT Product.ProNO ,Product.ProName FROM Product ,Proout WHERE Product.ProNO=Proout.ProNo GROUP BY Product.ProNO,ProName HAVING SUM (Price*Quantity)<100000 GO --单元十一 创建管理存储过程 --创建存储过程P_Sale1,统计每种产品的销售数量和销售金额 CREATE PROCEDURE P_Sale1 AS SELECT Product.ProNO,ProName ,Price ,SUM(Quantity),SM=SUM(Price*Quantity) FROM Proout,Product WHERE Product.ProNO=Proout.ProNo GROUP BY Product .ProNO,ProName,Price GO --创建存储过程P_Sale2,能够根据指定客户统计,汇总该客户购买每种产品的数量和花费金额 CREATE PROCEDURE P_Sale2 @CusNo nvarchar(3) AS SELECT Product.ProNO,ProName,Price ,SUM(Quantity),SUM(Price*Quantity) FROM Product,Proout WHERE CusNO=@CusNO AND Product.ProNO=Proout.ProNo GROUP BY Product .ProNO,ProName ,Price GO --创建存储过程P_Sale3,能够根据指定的产品编号和日期,以输出参数的形式得到该产品的销售金额 CREATE PROCEDURE P_Sale3 @ProNo nvarchar(5),@SaleDate DateTime,@MONEY Decimal(8,2)OUTPUT AS SET @MONEY=( SELECT SUM(Price*Quantity) FROM Proout,Product WHERE Product.ProNO=Proout.ProNo AND Product.ProNO=@ProNo AND SaleDate =@SaleDate GROUP BY Product .ProNO,ProName ,Price ) PRINT @MONEY GO --单元十二 触发器 --创建触发器,实现即时更新每种产品的库存数量。 CREATE TRIGGER UPDATE_ProNo_Stocks_TRIGGER ON Product FOR UPDATE AS PRINT'已即时更新每种产品的库存数量' GO --使用IF UPDATE(column)尽可能优化上题的触发器,以提高系统效率 ALTER TRIGGER UPDATE_ProNo_Stocks_TRIGGER ON Product FOR UPDATE AS IF UPDATE (ProNo) PRINT '已更新' GO --单元十三 游标 --创建存储过程P_SelProduct,逐行显示产品销售信息,内容包括编号、产品名称、销售日期、 --销售数量、销售金额、要求显示格式如下: --产品编号 产品名称 销售日期 销售数量 销售金额 --00001 电视 2006-1-1 10 30000 --产品编号 产品名称 销售日期 销售数量 销售金额 --00002 空调 2006-1-2 5 10000 CREATE PROCEDURE P_SelProduct AS DECLARE @ProNo NVARCHAR(5),@ProName nvarchar(20), @SaleDate DateTime,@Quantity Decimal(6,0), @SM Decimal(8,2) DECLARE CRS CURSOR FOR SELECT Product.ProNO,ProName,SaleDate,Quantity,SM=(Price*Quantity) FROM Product ,Proout WHERE Product .ProNO=Proout.ProNo ORDER BY SaleDate OPEN CRS FETCH NEXT FROM CRS INTO @ProNo,@ProName , @SaleDate,@Quantity ,@SM WHILE @@FETCH_STATUS =0 BEGIN PRINT '产品编号 产品名称 销售日期 销售数量 销售金额' PRINT @ProNo+' '+@ProName+' '+STR(YEAR(@SaleDate))+'-'+STR(MONTH(@SaleDate)) +'-'+STR(DAY(@SaleDate))+' '+@Quantity+' '+@SM+' ' FETCH NEXT FROM CRS INTO @ProNo,@ProName , @SaleDate,@Quantity , @SM END CLOSE CRS DEALLOCATE CRS t 扚 ]$ ]$ 晹轺褻蚅0! 17240671-14.2实训.sql [?灜? sql ?|--2018.4.18 USE master GO --单元五 创建于管理数据库 --创建数据库Sale CREATE DATABASE sale ON PRIMARY (NAME=sale, FILENAME='C:\\sale.mdf', SIZE=4MB, MAXSIZE=20MB, FILEGROWTH=1MB ) LOG ON (NAME=sale_log, FILENAME='C:\\sale_log.ldf', SIZE=10MB, MAXSIZE=20MB, FILEGROWTH=1MB) GO --向数据库增加文件组UserGroup ALTER DATABASE sale ADD FILEGROUP UserGroup GO ALTER DATABASE sale ADD FILE (NAME='sale_data3', FILENAME='D:\\sale_data3.ndf', SIZE=5MB, MAXSIZE=10MB, FILEGROWTH=1MB ) TO FILEGROUP UserGroup GO sp_help sale GO USE master GO -- 单元六 创建于管理数据表 --创建客户表结构Customer CREATE TABLE Customer (CusNO nvarchar(3) NOT NULL, CusName nvarchar(10), Address nvarchar(20)NOT NULL, Tel nvarchar(20) NOT NULL) GO --创建场品表结构Product CREATE TABLE Product (ProNO nvarchar(5) NOT NULL, ProName nvarchar(20)NOT NULL, Price Decimal(8,2) NOT NULL, Stocks Decimal(6,0) NOT NULL) GO --创建入库表结构Proln CREATE TABLE Proln (InputDate DateTime NOT NULL, ProNo nvarchar(5) NOT NULL, Quantity Decimal(6,0) NOT NULL) GO --创建销售表结构Proout CREATE TABLE Proout (SaleDate DateTime NOT NULL, CusNo nvarchar(3) NOT NULL, ProNo nvarchar(5) NOT NULL, Quantity Decimal(6,0) NOT NULL, Amount Decimal(8,2)NOT NULL) GO --向已创建的表添加数据 INSERT Customer VALUES('001','杨婷','深圳','0755-22221111') INSERT Customer VALUES('002','陈萍','深圳','0755-22223333') INSERT Customer VALUES('003','李东','深圳','0755-22225555') INSERT Customer VALUES('004','叶合','广州','0755-22227777') INSERT Customer VALUES('005','谭新','广州','0755-22229999') Go INSERT Product VALUES('00001','电视',3000.00,800) INSERT Customer VALUES('00002','空调',2000.00,500) INSERT Customer VALUES('00003','床',1000.00,300) INSERT Customer VALUES('00004','餐桌',1500.00,200) INSERT Customer VALUES('00005','音响',5000.00,600) INSERT Customer VALUES('00006','沙发',6000.00,100) Go INSERT Proln VALUES('2006-1-1','00001',10) INSERT Proln VALUES('2006-1-1','00002',5) INSERT Proln VALUES('2006-1-2','00001',5) INSERT Proln VALUES('2006-1-2','00003',10) INSERT Proln VALUES('2006-1-3','00001',10) INSERT Proln VALUES('2006-2-1','00003',20) INSERT Proln VALUES('2006-2-2','00001',10) INSERT Proln VALUES('2006-2-3','00004',30) INSERT Proln VALUES('2006-3-3','00003',20) Go INSERT ProOut VALUES('2006-1-1','001','00001',10) INSERT ProOut VALUES('2006-1-2','001','00002',5) INSERT ProOut VALUES('2006-1-3','002','00001',5) INSERT ProOut VALUES('2006-2-1','002','00003',10) INSERT ProOut VALUES('2006-2-2','001','00001',10) INSERT ProOut VALUES('2006-2-3','001','00003',20) INSERT ProOut VALUES('2006-3-2','003','00001',10) INSERT ProOut VALUES('2006-3-2','003','00004',30) INSERT ProOut VALUES('2006-3-3','002','00003',20) Go --单元七 实施数据完整性(约束) --使用ALTER TABLE 语句为已经创建的表添加主键约束、外键约束 --主键 ALTER TABLE Customer ADD CONSTRAINT PK_Customer PRIMARY KEY(CusNo) GO ALTER TABLE Product ADD CONSTRAINT PK_Product PRIMARY KEY(ProNo) GO --外键 ALTER TABLE Proout ADD CONSTRAINT FK_Proout_Product FOREIGN KEY(ProNo) REFERENCES Product(ProNo) GO ALTER TABLE Proout ADD CONSTRAINT FK_Proout_Customer FOREIGN KEY(CusNo) REFERENCES Customer(Customer) GO ALTER TABLE Proln ADD CONSTRAINT FK_Proln_Product FOREIGN KEY(ProNo) REFERENCES Product(ProNo) GO --约束客户表Customer的CosNo的列值长度为3,产品表Product 的ProNo 列值长度为5 ALTER TABLE Coustomer ADD CONSTRAINT CK_Customer_CusNo CHECK (CusNo like '[0-9][0-9][0-9]') GO ALTER TABLE Product ADD CONSTRAINT CK_Product_ProNo CHECK(ProNo like'[0-9][0-9][0-9][0-9][0-9]') GO --对产品表Product 的Stocks列、Price列、入库表Proln的Quanity列、销售表ProOut 的Quanity --列值进行约束,使其值大于0 ALTER TABLE Product ADD CONSTRAINT CK_Product_Stock CHECK(Stock>0) GO ALTER TABLE Product ADD CONSTRAINT CK_Product_Price CHECK(Price>0) GO ALTER TABLE Proln ADD CONSTRAINT CK_Proln_Quantity CHECK (Quantity>0) GO ALTER TABLE ProOut ADD CONSTRAINT CK_ProOut_Quantity CHECK(Quantity>0) GO --对销售表ProOut的SaleDate 列进行约束,当不输入值时,系统默认其值为系统当前日期 CREATE DEFAULT Today AS GETDATEA() GO /*ALTER TABLE ProOut ADD CONSTRAINT DF_ProOut_SaleDate DEFAULT('当前日期')FOR Date GO*/ --单元八 索引 --用户按照CusName查询客户信息,希望提高查询速度 CREATE UNIQUE INDEX IX_CusName ON Customer(CusName) GO --用户按照ProName查询产品信息,希望提高查询速度 CREATE UNIQUE INDEX IX_ProName ON Product(ProName) GO --用户按照SaleDate查询产品信息,希望提高查询速度 CREATE UNIQUE INDEX IX_SaleDate ON ProOut(SaleDate) GO --单元九 语言编程基础 --计算有多少种产品(假设为x),然后显示一条信息:共有X种产品 DECLARE @X int SET @X =(SELECT COUNT (*) FROM Product ) PRINT '共有'+convert (char(2),@x)+'种产品。' GO --编写计算n!(n=20)的程序,并显示结果。 DECLARE @X int,@product int SELECT @X=1,@product=1 WHILE @X<=20 BEGIN SELECT @X=@X+1 SELECT @product=@product*@X END SELECT '1*2*3*......*20的积'=@product GO --单元十 创建于管理视图 --创建视图V_Sale1,并显示销售日期、客户编号、客户姓名、产品编号、产品名称、单价 --销售数量、销售金额 CREATE VIEW V_Sale1 AS SELECT SaleDate,Customer.CusNO,CusName,Product.ProNO,ProName,Price,Proout.Quantity, SM=(Price *Proout.Quantity) FROM Customer ,Product,Proln,Proout WHERE Customer.CusNO=Proout.CusNo AND Product.ProNO=Proln.ProNo AND Product.ProNO=Proout.ProNo AND Proout.Quantity=Proln.Quantity GO --创建视图V-Sale2,统计每种产品的销售数量和销售金额。统计结果包括产品编号、 --产品名称、单价、销售数量和销售金额 CREATE VIEW V_Sale2 AS SELECT Product.ProNO ,ProName,Price,Proout.Quantity ,SM=(Price *Proout.Quantity) FROM Product ,Proout ,Proln GROUP BY ProName GO --创建视图V_Sale3,统计销售金额在10万以下的产品信息。 CREATE VIEW V_Sale3 AS SELECT Product.ProNO ,Product.ProName FROM Product ,Proout WHERE Product.ProNO=Proout.ProNo GROUP BY Product.ProNO,ProName HAVING SUM (Price*Quantity)<100000 GO --单元十一 创建管理存储过程 --创建存储过程P_Sale1,统计每种产品的销售数量和销售金额 CREATE PROCEDURE P_Sale1 AS SELECT Product.ProNO,ProName ,Price ,SUM(Quantity),SM=SUM(Price*Quantity) FROM Proout,Product WHERE Product.ProNO=Proout.ProNo GROUP BY Product .ProNO,ProName,Price GO --创建存储过程P_Sale2,能够根据指定客户统计,汇总该客户购买每种产品的数量和花费金额 CREATE PROCEDURE P_Sale2 @CusNo nvarchar(3) AS SELECT Product.ProNO,ProName,Price ,SUM(Quantity),SUM(Price*Quantity) FROM Product,Proout WHERE CusNO=@CusNO AND Product.ProNO=Proout.ProNo GROUP BY Product .ProNO,ProName ,Price GO --创建存储过程P_Sale3,能够根据指定的产品编号和日期,以输出参数的形式得到该产品的销售金额 CREATE PROCEDURE P_Sale3 @ProNo nvarchar(5),@SaleDate DateTime,@MONEY Decimal(8,2)OUTPUT AS SET @MONEY=( SELECT SUM(Price*Quantity) FROM Proout,Product WHERE Product.ProNO=Proout.ProNo AND Product.ProNO=@ProNo AND SaleDate =@SaleDate GROUP BY Product .ProNO,ProName ,Price ) PRINT @MONEY GO --单元十二 触发器 --创建触发器,实现即时更新每种产品的库存数量。 CREATE TRIGGER UPDATE_ProNo_Stocks_TRIGGER ON Product FOR UPDATE AS PRINT'已即时更新每种产品的库存数量' GO --使用IF UPDATE(column)尽可能优化上题的触发器,以提高系统效率 ALTER TRIGGER UPDATE_ProNo_Stocks_TRIGGER ON Product FOR UPDATE AS IF UPDATE (ProNo) PRINT '已更新' GO --单元十三 游标 --创建存储过程P_SelProduct,逐行显示产品销售信息,内容包括编号、产品名称、销售日期、 --销售数量、销售金额、要求显示格式如下: --产品编号 产品名称 销售日期 销售数量 销售金额 --00001 电视 2006-1-1 10 30000 --产品编号 产品名称 销售日期 销售数量 销售金额 --00002 空调 2006-1-2 5 10000 CREATE PROCEDURE P_SelProduct AS DECLARE @ProNo NVARCHAR(5),@ProName nvarchar(20), @SaleDate DateTime,@Quantity Decimal(6,0), @SM Decimal(8,2) DECLARE CRS CURSOR FOR SELECT Product.ProNO,ProName,SaleDate,Quantity,SM=(Price*Quantity) FROM Product ,Proout WHERE Product .ProNO=Proout.ProNo ORDER BY SaleDate OPEN CRS FETCH NEXT FROM CRS INTO @ProNo,@ProName , @SaleDate,@Quantity ,@SM WHILE @@FETCH_STATUS =0 BEGIN PRINT '产品编号 产品名称 销售日期 销售数量 销售金额' PRINT @ProNo+' '+@ProName+' '+STR(YEAR(@SaleDate))+'-'+STR(MONTH(@SaleDate)) +'-'+STR(DAY(@SaleDate))+' '+@Quantity+' '+@SM+' ' FETCH NEXT FROM CRS INTO @ProNo,@ProName , @SaleDate,@Quantity , @SM END CLOSE CRS DEALLOCATE CRS GO --单元十四 事务与锁 --1、一般情况下,只有当产品有足够的库存量时才允许销售该产品。创建一事务,实现当向Proout(销售)表插入新的数据行时,如果 --Stock(库存数)大于Quantity(销售数量),则允许销售,否则拒绝销售。 CREATE PROCEDURE P1 @SaleDate DateTime , @CusNo nvarchar(3), @ProNo nvarchar(5), @Quantity Decimal(6,0) AS BEGIN TRANSACTION INSERT Proout(SaleDate,CusNo,ProNo,Quantity) VALUES(@SaleDate ,@CusNo ,@ProNo,@Quantity ) DECLARE @CountNum INT SET @CountNum =(SELECT Stocks FROM Product WHERE ProNo=@ProNo)-(SELECT SUM(Quantity) FROM Proout WHERE ProNo=@ProNo) IF @CountNum<0 BEGIN ROLLBACK TRANSACTION PRINT '库存数量小于销售数量,拒绝销售。' END ELSE BEGIN COMMIT TRANSACTION PRINT '销售成功!' END GO --测试 INSERT INTO Proout VALUES('2016-6-1','002','000001',900) GO --2、不用触发器,用事务的方式实现:当产品入库和销售时能保证库存数量的准确性。谈谈你对触发器实现和使用事务实现的理解 t ? + + G鹙坺BwL0 17240671-2.sql 饌? --2018年3月14日 USE Xk GO --查询“00000001”同学是否报了“003”课程 SELECT * From StuCou where StuNo='00000001' and CouNo='003' GO --查询报名人数在15-40范围内的课程信息 SELECT * FROM Course WHERE WillNum>=15 AND WillNum<=40 GO --Between...and... SELECT * FROM Course WHERE WillNum BETWEEN 15 AND 40 GO --查询课程编号分别为"004"、"007"、"013"的课程信息(理解or) SELECT * FROM Course WHERE CouNo='004' or CouNo='007' or CouNo='013' GO --in的用法 SELECT * FROM Course WHERE CouNo IN ('004','007','013') GO --查询课程编号分别不为"004"、"007"、"013"的课程信息(not) SELECT * FROM Course WHERE CouNo NOT IN ('004','007','013') GO --查询课程信息、报名人数占限选人数之比(表达式作为列) SELECT * , WillNum/LimitNum AS '报名人数占限选人数之比' FROM Course GO --补充问题:小数点只保留2位(convert()函数、cast()函数) SELECT * ,convert (decimal(4,2),WillNum/LimitNum) AS '报名人数占限选人数之比' FROM Course GO SELECT * ,cast (WillNum/LimitNum as decimal(4,2)) AS '报名人数占限选人数之比' FROM Course GO --查询课程信息、报名人数占限选人数之比(升ASC、降DESC 序) SELECT * ,cast (WillNum/LimitNum as decimal(4,2)) AS '报名人数占限选人数之比' FROM Course ORDER BY WillNum DESC GO --查询课程信息、报名人数占限选人数之比以降序排列并查询前10行(前10%) SELECT top 10 * ,cast (WillNum/LimitNum as decimal(4,2)) AS '报名人数占限选人数之比' FROM Course ORDER BY WillNum DESC GO --查询选修课的任课教师名、课程号、课程名。要求教师名降序排列,教师名相同时,按课程号的升序排列 SELECT teacher as '教师名',CouNo as '课程号',CouName as '教程名' FROM Course ORDER BY Teacher DESC,CouNo ASC GO --查询课程信息,要求查询结果为(在查询结果增加字符串) SELECT '课程编码'=CouNO,'课程名称为:','课程名称'=CouName FROM Course GO --查询带有‘制作’课程 SELECT '课程编码'=CouNO,'课程名称为:','课程名称'=CouName FROM Course WHERE CouName LIKE '%制作%' GO -2018年3月17日 USE Xk GO 查询选课表随机数无值的数据行 SELECT * FROM StuCou WHERE RandomNum IS NULL GO SELECT * FROM Course GO --查看选课表有多少门课程 --COUNT函数 SELECT COUNT(*)AS '课程总门数' FROM Course GO SELECT COUNT(CouNo)AS '课程总门数' FROM Course GO SELECT COUNT(*)FROM StuCou GO SELECT COUNT(RandomNum) FROM StuCou GO SELECT COUNT(Kind)AS '课程总门数' FROM Course GO --t ? ? ? 广~燪uL0 17240671-3.sql 餷wY--2018-3-21 USE Xk GO --1.平均 SELECT AVG(*)FROM Cours GO --2 SELECT Coure(*)FROM Student GO --3 --4 SELECT COUNT(DITINCT Kind) FROM Course FROM Course GO --5按照课程类别分组统计各类课程的门 SELECT Kind AS '课程种类',COUNT(Kind) AS '该种类的课程' FROM Course GROUP BY Kind GO --6 SELECT MIN(willNum) as'最报名人',MAX(willNum) as '最多报名人' FROM Course WHERE willNum >15 GROUP By Kind --7 SELECT Kind,AVG(WillNum) FROM Course WHERE WillNum>15 GROUP BY Kind HAVING AVG(WillNum)>30 GO --8 SELECT Kind,AVG(WillNum) FROM Coure WHERE Kind IN('管理')OR Kind GROUP BY ALL Kind GO SELECT * FROM Course COMPUTE By DepartNo COMPUTE AVG(WillNum) By DepartNo GO甬t ? O O 泎蝼P|L0 17240671-4.sql 餺9?-2018年3月28日 USE Xk GO --4, SELECT Student.StuNo,StuName,Course,CouNo,CouName,Credit FROM Student Course,StuCou WEHERE Student.StuNo = StuCou.StuNo AND COurse.CouNo.CouNo ORDER BY CouName,Student.StuNo GO --方法2 SELECT Student.StuNo,StuName,Course,CouNo,CouName,Credit FROM Student JOIN StuCou ON Student.StuNo = StuCou.StuNo JOIN Course ON Course CouNo = StuCou.StuNo ORDER BY CouName,Student.StuNo GO /*--查询同学报名‘计算机应用工工程系’选修课程的情况,显示信息包括:学号,姓名,课程编号,课程名,教师,上课时间,按照课程编号排序, 课程编号相同时,按照学号排序*/ SELECT Student.StuNo,StuName,CouNo,CouName,Teacher,ScoolTime FROM Student,Course,StuCou WHERE Student.StuNo=StuCou.StuNo AND Course=StuCou.CouNo AND DepartName='计算机工程系' AND Department.DepartNo=Course.DepartNo ORDER BY Course.CouNo,Student.StuNo GO --修改使用别名完成上题 SELECT Student.StuNo,StuName,CouNo,CouName,Teacher,ScoolTime FROM Student JOIN StuCou SC ON S.StuNo = SC.StuNo JOIN Course C ON C.CouNo = SC.CouNo JOIN Department D ON D.DepartNo=C.DepartNo WHERE DepartName='计算机工程系' ORDER BY C.CouNo,S.StuNo GO --练一练,查询各班同学的信息,要求显示,班级编号,班级名称,学号,姓名,按照班级编号排序,当班级编号相同时,按照学号排序 --课本73页[2.35]查询每个班级可以选修的,不是自己所在系部开设的选修课程信息,显示信息包括班级,课程名,课程种类, --学分,老师,上课时间和报名人数。 SELECT '班级编号'=ClassNo'班级名称','课程名'=CouName,'课程种类'=Kind,'学分'=Credit,'老师'=Teacher,'上课时间'=ScoolTime, '报名人数'=WillNum FROM Class,Course WHERE Class.DepartNo<>Course.DEpartNo GO --课本73页[2.36] --查询课程类别相同但开课系部不同的课程信息,要求显示课程编号,课程名称,课程类别,系部编号,按照课程编号升序排序 SELECT '课程编号'=C1.CouNo,'课程名称'=C1.CouName,'课程类别'=C1.Kind,'系部编号'=C1.DepartNo FROM Course C1,Course C2 WHERE C1,Kind=C2.Kind AND C1.DepartNo<>C2.DEpartNo ORDER BY 课程编号 GO --外连接 --观察如下查询数据 --查询课程信息 SELECT CouNo,CouName,WillNum FROM Course ORDER BY CouNo GO --查询所有同学报名选修课的情况(包括有报名和没人报名),显示学号,姓名,课程号,课程名。 SELECT '学号'=CouNo,'姓名'=StuName,'课程号'=CouNo,'课程名'=CouName FROM Student,Course,StuCou WHERE Course.CouNo=StuCou.CouNo GO --丢失了没人报名的019课程,使用外连接信息丢失的问题 SELECT '学号'=StuNo,'姓名'=StuName,'课程号'=CouNo,'课程名'=CouName FROM Course LEFT JOIN StuCou /*左外连接,解决的是JOIN左面的表丢失的数据*/ ON Course.CouNo=StuCou.StuNo ORDER BY Course.CouNo GO --查询选修表信息 SELECT CouNo FROM StuCou ORDER BY CouNo GO`}t ? K K ?n⑾P凩0 17240671-5.sql 餹鱧--2018年4月4日 USE Xk GO --1,学号为'00000025'的学生第一志愿报名选修"001"课程.请在数据库进行处理.(增加数据进StuCou表) SELECT * FROM StuCou WHERE StuNo='00000025' GO INSERT StuCou(StuNo,CouNo,WillOrder,State) VALUES('00000025','001',1,'报名') GO --2,删除学号为'00000025'的学生的选修课报名信息。 DELETE StuCou WHERE StuNo='00000025' AND CouNo='01' GO UPDATE Course SET WillNum=WillNum-1 WHERE CouNo='001' --3,将"00多媒体"班的"杜晓静"的名字修改为"杜小静"。 UPDATE Student SET StuName='杜小静' FROM Student.Class WHERE StuName='杜晓静' AND ClassName='00多媒体' AND Student.ClassNo=Class.ClassNo --4,"00电子商务"班的"林斌"申请将已选修的"网络信息检索原理与技术"课程修改为"Linux操作系统". UPDATE StuCou SET CouNo = (SELECT CouNo FROM Course WHERE CouName = 'Linux操作系统') FROM StuCou,Class,Student,Course WHERE Class.Class Student.StuName = '林斌' AND CouName = '网络信息检索原理与技术' AND Class.ClassNo = Student.ClassNo AND Student.StuNo = StuCou.StuNo AND Name = '00电子商务' AND Course.CouNo = StuCou.CouNo 见t ? ? ? 剮L0 17240671-6-2.sql ?? USE master GO CREATE DATABASE Sale ON (NAME=Sale, FILENAME='E:\\Sale.mdf', SIZE=4, MAXSIZE=10, FILEGROWTH=1) LOG ON (NAME=Sale_log, FILENAME='F:\\Sale_log.ldf', SIZE=2, MAXSIZE=10, FILEGROWTH=1) GO USE Sale GO ALTER DATABASE Sale ADD FILEGROUP UserGroup GO USE master GO ALTER DATABASE Sale ADD FILE (NAME=Sale, FILENAME='E:\\Sale2.ndf', SIZE=5MB, MAXSIZE=10MB, FILEGROWTH=1MB) TO FILEGROWOUP UserGroup GO SP_helpdb Sale GO?t ? ? ? ╡?WP扡0 17240671-7-1sql 餋嘵--2018年4月18日第七周 USE Xk GO ALTER DATABASE Xk ADD FILEGROUP TableGroup GO sp_helpfilegroup TableGroup GO USE Xk GO --创建班级信息表Class CREATE TABLE Class1 (ClassNo nvarchar (8) NOT NULL, ClassName nvarchar (20) NOT NULL, DepartNo nvarchar (2) NOT NULL) GO --创建学生信息表Student CREATE TABLE Student1 (StuNo nvarchar (8) NOT NULL, StuName nvarchar (10) NOT NULL, Pwd nvarchar (8) NOT NULL, ClassNo nvarchar (8) NOT NULL) GO --创建学生选课表StuCou CREATE TABLE StuCou1 (StuNo nvarchar (8) NOT NULL, CouNo nvarchar (3) NOT NULL, WillOrder smallint NOT NULL, State nvarchar (2) NOT NULL, RandomNum nvarchar (50) NULL) GO USE Xk GO ALTER TABLE Student ADD birthday datetime null,bz nvarchar(20) null GO USE Xk GO ALTER TABLE Student DROP COLUMN birthday GO USE Xk GO ALTER TABLE Student ALTER COLUMN bz nvarchar(30) null GO USE Xk GO sp_rename 'Student.bz','StuBz','COLUMN' GO 鮰 ? ? ? E諹wE汱0 17240671-7-2.sql ?_2 USE master GO CREATE DATABASE Sale ON (NAME=Sale, FILENAME='C:\\Sale.mdf', SIZE=4, MAXSIZE=10, FILEGROWTH=1) LOG ON (NAME=Sale_log, FILENAME='C:\\Sale_log.ldf', SIZE=2, MAXSIZE=10, FILEGROWTH=1) GO USE Sale CREATE TABLE Customer (CusNo nvarchar(3) NOT NULL, CusName nvarchar(10) NOT NULL, Address nvarchar(20) NULL, Tel nvarchar(20) NULL) GO CREATE TABLE Product (ProNo nvarchar(5) NOT NULL, ProName nvarchar(20) NOT NULL, Price Decimal(8,2) NOT NULL, Stocks Decimal(8,0) NOT NULL) GO CREATE TABLE Proln (InputDate DateTime NOT NULL, ProNo nvarchar(5)NOT NULL, Quantity Decimal(6,0)NOT NULL) GO CREATE TABLE ProOut (SaleDate DateTime NOT NULL, CusNo nvarchar(3)NOT NULL, ProNo nvarchar(5)NOT NULL, Quantity Decimal(6,0)NOT NULL) GO INSERT Customer VALUES ('001','杨婷','深圳','0755-22221111') INSERT Customer VALUES ('002','陈萍','深圳','0755-22223333') INSERT Customer VALUES ('003','李东','深圳','0755-22225555') INSERT Customer VALUES ('004','叶合','广州','0755-22225555') INSERT Customer VALUES ('005','谭新','广州','0755-22225555') GO INSERT Proln VALUES ('2006-1-1','00001','10') INSERT Proln VALUES ('2006-1-2','00002','5') INSERT Proln VALUES ('2006-1-3','00001','5') INSERT Proln VALUES ('2006-2-1','00003','10') INSERT Proln VALUES ('2006-2-2','00001','10') INSERT Proln VALUES ('2006-2-3','00003','10') INSERT Proln VALUES ('2006-3-2','00001','10') INSERT Proln VALUES ('2006-3-2','00004','30') INSERT Proln VALUES ('2006-3-3','00003','20') GO --添加主键约束,外键约束 ALTER TABLE Customer ADD CONSTRAINT PK_Customer PRIMARY KEY(CusNo) GO ALTER TABLE Product ADD CONSTRAINT PK_Product PRIMARY KEY(ProNo) GO ALTER TABLE Proln ADD CONSTRAINT PK_Proln PRIMARY KEY(ProNo) GO ALTER TABLE ProOut ADD CONSTRAINT PK_ProOut PRIMARY KEY(CusNo,ProNo) GO --运用检查约束 ALTER TABLE Product ADD CONSTRAINT CK_Stock CHECK(Stock>0) ALTER TABLE Product ADD CONSTRAINT CK_Price CHECK(Price>0) ALTER TABLE Proln ADD CONSTRAINT CK_Quantity CHECK(Quantity>0) ALTER TABLE ProOut ADD CONSTRAINT CK_Quantity CHECK(Quantity>0) GO --运用默认约束 ALTER TABLE ProOut ADD CONSTRAINT DF_ProOut_Saledate DEFAULT('当前日期')FOR Date GO?t ? ? ? €猳?Q㎜0 17240671.10.1.sql 皝?--2018-4-9日 编程基础 SELECT ClassNo From Xk..Class GO SELECT CLassNo FROM Xk.dbo.Class GO --T_sql语法元素:标识符(两种),局部变量,全局变量,数据类型 /* */ SELECT @@SERVERNAME SELECT @@MAX_CONNECTIONS SELECT @@LANGUAGE SELECT @@VERSION SELECT * FROM Xk..Student GO SELECT * FROM Class GO USE Xk SELECT * FROM Xk..Student GO USE Xk CREATE VIEW V TEST AS SELECT * FROM Student GO USE Xk GO CREATE VIEW V TEST AS SELECT * FROM Student GO DECLARE @iNUM INT SET @iNUM=5 PRINI @INUM --显示Course表有多少类课程? SELECT COUNT(DISTINCT Kind)FROM Course GO --显示Course表有多少类课程,要求将结果保存到一个局部变量,并显示出来。 DECLARE @KindCount Tinyint SET @KindCount=(SELECT COUNT (DISTINCT Kind)FROM Course) PRINT @KindCount GO DECLARE @KindCount Tinyint SET @KindCount=(SELECT COUNT (DISTINCT Kind)FROM Course) PRINT 'Course表有'+CONVERT (VARCHAR(3),@KindCount)+'类课程' GO --练一练:1,编写计算1+2+3+10000的和,并显示计算结果。 DECLARE @i int,@sum=0 SELECT @i=1,@sum=0 WHILE @i<=10000 BEGIN SELECT @sum=@sum+@i SELECT @i=@i+1 END SELECT'1+2+3+4+......+10000的和'=@sum GO --练一练:2,编写计算20!,并显示计算结果。 --练一练:3,@iNum1,@iNum2为两个整型变量,值分为76,90,编程显示两个变量的较大者。 DECLARE @iNum1 int,@iNum2 int SELECT @iNum1=76,@iNum2=90 IF(@iNum1>@iNum2) PRINT @iNum1 ELSE PRINT @iNum2 GO]謙 ? ? ? ;砝blO獿0 17240671.10.2.sql 餹M--2018-05-11 DECLARE @iNum1 int,@iNum2 int SELECT @iNum1=79,@iNum2=90 if(@iNum1>@iNum2) PRINT @iNum1 else PRINT @iNum2 GO USE Xk GO SELECT '课程类别'=Kind,'分类的课程类别'= CASE Kind WHEN '工程技术'THEN'工科类课程' WHEN '人文'THEN'人文类课程' WHEN '信息技术'THEN '信息技术类课程' ELSE '其他类课程' END,'课程名称'=CouName,'报名人数'=WillNum FROM Course ORDER BY Kind,WillNum COMPUTE AVG(WillNum)BY Kind GO --问题9.13校长生日1979/12/23,使用日期函数显示校长年龄 SELECT '年龄'=DATEDIFF(YY,'1979/12/23',GETDATE()) GO --如果一个人的出生日期为1922/2/23,计算并显示目前总天数 SELECT '天数'=DATEDIFF(DD,'1922/2/23',GETDATE()) GO --问题9.26 CREATE FUNCTION CalcRemainNum (@X decimal(6,0),@Y decimal(6,0)) RETURNS decimal(6,0) AS BEGIN RETURN(@X-@Y) END GO ALTER TABLE Course ADD RemainNum AS dbo.CalcRemainNum(LimitNum,ChooseNum) GO SELECT *FROM Course GO  ? c c ?/fP癓0 17240671.10.4.sql 饃XK--2018-05-16 --创建一个名字为V_MyClass的视图。 CREATE VIEW V_MyClass AS SELECT StuNo,StuName,ClassName FROM Student,Class WHERE Student.ClassNo=Class.ClassNo GO --对视图可以像使用表一样操作。 --查看视图内容。 SELECT * FROM V_MyClass GO --查看视图的定义。 SP_HELPTEXT V_MyClass GO --修改视图,加密视图的定义。 ALTER VIEW V_MyClass WITH ENCRYPTION AS SELECT StuNo,StuName,ClassName FROM Student,Class WHERE Student.ClassNo=Class.ClassNo GO --查看视图的定义。 SP_HELPTEXT V_MyClass GO --显示"对象'V_MyClass'的文本已加密。" --重命名视图。 SP_RENAME 'V_MyCLass','V1_MyClass' GO --删除视图。 DROP VIEW V_MyClass GO SP_HELP GO --[问题10.1]修改试图列标题 --[问题10.6]注意视图SELECT语句必须有列名。 /* 综合练习:Teacher 是00多媒体班班主任,使该老师可以查看自己班级学生选课情况(学号,姓名,课程名,种类, 学分,上课时间,开课习部) */ --步骤1:创建一个视图,显示'00多媒体'班同学的选课情况(学号,姓名,课程名,种类,学分,上课时间,开课系部) CREATE VIEW V_TeacherLi AS SELECT Student,StuNo,StuName,CouName,Kind,Credit,ScoolTime,DepartName FROM Student,Course,StuCou,Class,Department WHERE Student.StuNo=StuCou.StuNo AND Course.CouNo=StuCou.CouNo AND Student.ClassNo=Class.Class.ClassNo AND Department.DepartNo=Course.DepartNo AND ClassName GO --步骤2;在SQL Server为TeacherLi创建一个登录,登录名为:TeacherLi,登录密码为:TeacherLi USE master GO CREATE LOGIN TeacherLi WITH PASSWORD='TeacherLi' GO --测试:使用TeacherLi登录SQL Server,看是否可以登录成功? --可以登录成功。看不到Xk数据库数据。 --步骤3; USE Xk GO CREATE USER TeacherLi GO --测试:使用TeacherLi登录SQL Server,看是否可以登录成功? --可以点Xk,但是看不到用户表 --步骤4:授予TeacherLi可以看到视图V_TeacherLi USE Xk GO GRANT SELECT ON V_TeacherLi TO TeacherLi GO GRANT SELECT ON STUDENT TO TeacherLi GO 鏒t 扚 ? ? 侘絿禖睱0! 17240671.10.5实训.sql [?灜? sql 皭?--2018.4.18 USE master GO --创建数据库Sale CREATE DATABASE sale ON PRIMARY (NAME=sale, FILENAME='C:\\sale.mdf', SIZE=4MB, MAXSIZE=20MB, FILEGROWTH=1MB ) LOG ON (NAME=sale_log, FILENAME='C:\\sale_log.ldf', SIZE=10MB, MAXSIZE=20MB, FILEGROWTH=1MB) GO --向数据库增加文件组UserGroup ALTER DATABASE sale ADD FILEGROUP UserGroup GO ALTER DATABASE sale ADD FILE (NAME='sale_data3', FILENAME='D:\\sale_data3.ndf', SIZE=5MB, MAXSIZE=10MB, FILEGROWTH=1MB ) TO FILEGROUP UserGroup GO sp_help sale GO USE master GO --创建客户表结构Customer CREATE TABLE Customer (CusNO nvarchar(3) NOT NULL, CusName nvarchar(10), Address nvarchar(20)NOT NULL, Tel nvarchar(20) NOT NULL) GO --创建场品表结构Product CREATE TABLE Product (ProNO nvarchar(5) NOT NULL, ProName nvarchar(20)NOT NULL, Price Decimal(8,2) NOT NULL, Stocks Decimal(6,0) NOT NULL) GO --创建入库表结构Proln CREATE TABLE Proln (InputDate DateTime NOT NULL, ProNo nvarchar(5) NOT NULL, Quantity Decimal(6,0) NOT NULL) GO --创建销售表结构Proout CREATE TABLE Proout (SaleDate DateTime NOT NULL, CusNo nvarchar(3) NOT NULL, ProNo nvarchar(5) NOT NULL, Quantity Decimal(6,0) NOT NULL, Amount Decimal(8,2)NOT NULL) GO --向已创建的表添加数据 INSERT Customer VALUES('001','刘星','深圳','0755-22221111') INSERT Customer VALUES('002','陈笃','深圳','0755-22223333') INSERT Customer VALUES('003','李耳','深圳','0755-22225555') INSERT Customer VALUES('004','苏岩','广州','0755-22225555') INSERT Customer VALUES('005','赵颖','广州','0755-22225555') Go INSERT Customer VALUES('0001','电视','3000.00','800') INSERT Customer VALUES('0002','空调','2000.00','500') INSERT Customer VALUES('0003','床','1000.00','300') INSERT Customer VALUES('0004','餐桌','1500.00','200') INSERT Customer VALUES('0005','音响','5000.00','600') INSERT Customer VALUES('0006','沙发','6000.00','100') Go INSERT Proln VALUES('2006-1-1','00001','10') INSERT Proln VALUES('2006-1-2','00002','5') INSERT Proln VALUES('2006-1-3','00001','5') INSERT Proln VALUES('2006-2-1','00003','10') INSERT Proln VALUES('2006-2-2','00001','10') INSERT Proln VALUES('2006-2-3','00003','20') INSERT Proln VALUES('2006-3-2','00001','10') INSERT Proln VALUES('2006-3-2','00004','30') INSERT Proln VALUES('2006-3-3','00003','20') Go INSERT ProOut VALUES('2006-1-1','001','00001','10','5000') INSERT ProOut VALUES('2006-1-2','001','00002','5','4000') INSERT ProOut VALUES('2006-1-3','002','00001','5','7000') INSERT ProOut VALUES('2006-2-1','002','00003','10','6000') INSERT ProOut VALUES('2006-2-2','001','00001','10','4000') INSERT ProOut VALUES('2006-2-3','001','00003','20''6000') INSERT ProOut VALUES('2006-3-2','003','00001','10','5500') INSERT ProOut VALUES('2006-3-2','003','00004','30') INSERT ProOut VALUES('2006-3-3','002','00003','20') Go --使用ALTER TABLE 语句为已经创建的表添加主键约束、外键约束 ALTER TABLE Customer ADD CONSTRAINT PK_Customer PRIMARY KEY(CusNo) GO ALTER TABLE Product ADD CONSTRAINT PK_Product PRIMARY KEY(ProNo) GO ALTER TABLE Proln ADD CONSTRAINT PK_Proln PRIMARY KEY(ProNo) GO ALTER TABLE ProOut ADD CONSTRAINT PK_ProOut PRIMARY KEY(CusNO,ProNo) GO --约束客户表Customer的CosNo的列值长度为3,产品表Product 的ProNo 列值长度为5 ALTER TABLE Coustomer ADD CONSTRAINT CK_CusNo CHECK (CusNo like '[0-9][0-9][0-9]') GO ALTER TABLE Product ADD CONSTRAINT CK_ProNo CHECK(ProNo like'[0-9][0-9][0-9][0-9][0-9]') GO --对产品表Product 的Stocks列、Price列、入库表Proln的Quanity列、销售表ProOut 的Quanity --列值进行约束,使其值大于0 ALTER TABLE Product ADD CONSTRAINT CK_Stock CHECK(Stock>0) ALTER TABLE Product ADD CONSTRAINT CK_Price CHECK(Price>0) ALTER TABLE Proln ADD CONSTRAINT CK_Quantity CHECK (Quantity>0) ALTER TABLE ProOut ADD CONSTRAINT CK_Quantity CHECK(Quantity>0) GO --对销售表ProOut的SaleDate 列进行约束,当不输入值时,系统默认其值为系统当前日期 ALTER TABLE ProOut ADD CONSTRAINT DF_ProOut_SaleDate DEFAULT('当前日期')FOR Date GO --用户按照CusName查询客户信息,希望提高查询速度 CREATE UNIQUE INDEX IX_CusName ON Customer(CusName) GO --用户按照ProName查询产品信息,希望提高查询速度 CREATE UNIQUE INDEX IX_ProName ON Product(ProName) GO --用户按照SaleDate查询产品信息,希望提高查询速度 CREATE UNIQUE INDEX IX_SaleDate ON ProOut(SaleDate) GO --计算有多少种产品(假设为x),然后显示一条信息:共有X种产品 DECLARE @X int SET @X =(SELECT COUNT (*) FROM Product ) PRINT '共有'+convert (char(2),@x)+'种产品。' GO --编写计算n!(n=20)的程序,并显示结果。 DECLARE @X int,@product int SELECT @X=1,@product=1 WHILE @X<=20 BEGIN SELECT @X=@X+1 SELECT @product=@product*@X END SELECT '1*2*3*......*20的积'=@product GO --创建视图V_Sale1,并显示销售日期、客户编号、客户姓名、产品编号、产品名称、单价 --销售数量、销售金额 CREATE VIEW V_Sale1 AS SELECT SaleDate,Customer.CusNO,CusName,Product.ProNO,ProName,Price,Proout.Quantity, COUNT (*)Amount FROM Customer ,Product,Proln,Proout WHERE Customer.CusNO=Proout.CusNo AND Product.ProNO=Proln.ProNo AND Product.ProNO=Proout.ProNo AND Proout.Quantity=Proln.Quantity GO --创建视图V-Sale2,统计每种产品的销售数量和销售金额。统计结果包括产品编号、 --产品名称、单价、销售数量和销售金额 CREATE VIEW V_Sale2 AS SELECT Product.ProNO ,ProName,Price,Proout.Quantity ,COUNT(*)AMOUNT FROM Product ,Proout ,Proln GROUP BY ProName GO --创建视图V_Sale3,统计销售金额在10万以下的产品信息。 CREATE VIEW V_Sale3 AS SELECT Product.ProNO ,Product.ProName FROM Product ,Proout WHERE Product.ProNO=Proout.ProNo GROUP BY Product.ProNO,ProName HAVING SUM (Price*Quantity)<100000 GO &鉻 ? 鎼?跴睱0 17240671.10.6.sql 鹦?--2018-5-18 第11周周五 --存储过程 --[问题11.1],[问题11.2] USE Xk GO CREATE PROCEDURE P_Student AS SELECT * FROM Student WHERE ClassNo='20000001' GO --执行存储过程 P_Student GO --查看存储过程 SP_HELP P_Student GO SP_HELPTEXT P_Student GO SP_DEPENDS P_Student GO CREATE PROCEDURE P_StudentPara @ClassNo nvarchar(8) AS SELECT * FROM Student WHERE ClassNo=@ClassNo GO EXEC P_StudentPara '20000001' GO --[问题11.4] --问题:带参数的存储过程时传递参数有几种方式? --如何创建和执行带输出参数的存储过程?[问题11.7] EXEC P_StudentPara @ClassNo='20000001' GO EXEC P_StudentPara @ClassNo='20000002' GO CREATE PROCEDURE P_ClassNum @ClassNo nvarchar (8),@ClassNum smallint OUTPUT AS SET @ClassNum= ( SELECT COUNT(*)FROM Student WHERE ClassNo=@ClassNo=@ClassNo ) PRINT @ClassNum GO DECLARE @ClassNo nvarchar (8),@ClassNum smallint SET @ClassNo='20000001' EXEC P_ClassNum @ClassNo,@ClassNum OUTPUT SELECT @ClassNum GO ALTER PROCEDURE P_StudentPara @ClassName nvarchar(20) WITH ENCRYPTION AS SELECT ClassName,StuNo,StuName,Pwd FROM Student,Class WHERE Student.ClassNo=Class.ClassNo AND ClassName LIKE '%'+@ClassName+'%' GO USE master GO XP_LOGINCONFIG GO XP_CMDSHELL 'DIR D:\*.*' GO 挌t ? ? ? RE粣甈筁0 17240671.12.1.sql 養--2018年5月25日 --12.1创建触发器Update_Student_Trigger,实现每当修改Student表的数据时,在客户端显示"已修改Student表的数据。"的消息。 USE Xk GO CREATE TRIGGER Update_Student_Trigger ON Student FOR UPDATE AS PRINT'已修改Student表的数据。' GO UPDATE Student SET Pwd='11111111' WHERE StuNo='00000001' --12.2修改触发器Update_Student_Trigger,在确实修改了Student表的数据后返回"已修改Student表的数据。",否则返回"不存在要修改的数据。"。 USE Xk GO ALTER TRIGGER Update_Student_Trigger ON Student FOR UPDATE AS IF(SELECT COUNT(*) FROM inserted)<>0 PRINT'已修改 Student 表的数据。' ELSE PRINT '不存在要修改的数据。' GO --12.4创建替代触发器UPDATE_Department_Trigger,修改Department表的数据时触发器发器,用执行触发器的语句替代触发的SQL语句。 USE Xk GO CREATE TRIGGER UPDATE_Department_Trigger ON Department INSTEAD OF UPDATE AS PRINT'实际上并没有修改Department表的数据。' GO UPDATE Department SET DepartName='软件工程系'WHERE DepartNo='01' --12.5创建一个触发器,当插入,更新或删除StuCou表的选课数据行时,能同时更新Course表相应的报名人数。 USE Xk GO CREATE TRIGGER SetWillNum ON StuCou FOR INSERT,UPDATE,DELETE AS UPDATE Course SET WillNum=WillNum+1 WHERE CouNo=(SELECT CouNo FROM INSERTED) UPDATE Course SET WillNum=WillNum-1 WHERE CouNo=(SELECT CouNo FROM DELETED) PRINT '已自动更新Course 表相应课程的报名人数。' GO SELECT * FROM Course WHERE CouNo='002' SELECT * FROM Course WHERE CouNo='003'|鵷 ? 魸儕擯綥0 17240671.13.1.sql 鹭贒--2018-05-30 USE Xk GO SELECT * FROM Student WHERE StuName LIKE '张%' GO --创建一个游标,逐渐显示姓张同学的信息 --步骤1:声明游标 DECLARE CUR_StuName CURSOR FOR SELECT * FROM Student WHERE StuName LIKE '张%' GO --打开游标 OPEN CUR_StuName --显示游标位置的数据行 FETCH CUR_StuName WHILE @@FETCH_STATUS=0 FETCH CUR_StuName GO SELECT @@FETCH_STATUS --关闭游标 CLOSE CUR_StuName --释放游标 DEALLOCATE CUR_StuName GO --任意给出学号,然后允许修改名字。使用游标完成。 CREATE PROCEDURE P_StuName @StuNo nvarchar(8),@StuName nvarchar(10) AS --用来接收FETCH的数据行 DECLARE @StuNo nvarchar(8),@StuName nvarchar(10),@ClassNo nvarchar(8),@Pwd nvarchar(8) --声明游标 DECLARE CUR_StuName CURSOR FOR SELECT * FROM Student --打开游标 OPEN CUR_StuName --FETCH游标位置的数据到4个变量里 FETCH CUR_StuName INTO @StuNo,@StuName,@ClassN0,@Pwd WHILE @@FETCH_STATUS=0 BEGIN IF(@StuNo=@InputStuNo) UPDATE Student SET StuName=@InputStuName WHERE CURRENT OF CUR_StuName FETCH CUR_StuName INTO @StuNo,@StuName,@ClassNo,@Pwd END --关闭游标 CLOSE CUR_StuName --释放游标 DEALLOCATE CUR_StuName GO --执行,将'00000046' '张峰'名字改为'张锋' P_StuName '00000046','张锋' GO g豻 ? ` ` )锋?P芁0 17240671.14.1.sql 版蕂--2018-06-06 USE Xk GO --开始事务,一个学生报3门课 BEGIN TRANSACTION INSERT StuCou(StuNo,CouNo,WillOrder,State) VALUES ('00000025','001',1) INSERT StuCou(StuNo,CouNo,WillOrder,State) VALUES ('00000025','002',2) INSERT StuCou(StuNo,CouNo,WillOrder,State) VALUES ('00000025','003',3) --提交事务,保存在StuCou表 COMMIT TRANSACTION SELECT * FROM StuCou WHERE StuNo='00000025' GO BEGIN TRANSACTION INSERT StuCou(StuNo,CouNo,WillOrder,State) VALUES ('00000025','001',1,'报名') INSERT StuCou(StuNo,CouNo,WillOrder,State) VALUES ('00000025','002',2,'报名') INSERT StuCou(StuNo,CouNo,WillOrder,State) VALUES ('00000025','003',3,'报名') --撤销事务,撤销刚插入的3行数据 ROLLBACK TRANSACTION SELECT * FROM StuCou WHERE StuNo='00000025' GO USE Xk GO BEGIN TRANSACTION --报3门课程 INSERT StuCou(StuNo,CouNo,WillOrder) VALUES ('00000025','001',1) INSERT StuCou(StuNo,CouNo,WillOrder) VALUES ('00000025','002',2) INSERT StuCou(StuNo,CouNo,WillOrder) VALUES ('00000025','003',3) DECLARE @CountNum INT SET @CountNum=(SELECT COUNT(*)FROM StuCou WHERE StuNo='00000025') IF @CountNum>3 BEGIN ROLLBACK TRANSACTION PRINT '报名的课程超过所规定的3门,所以报名无效。' END ELSE BEGIN COMMIT TRANSACTION PRINT '恭喜,选修课程报名成功!' END --测试 SELECT *FROM StuCou WHERE StuNo='00000025' --删除 DELETE FROM StuCou WHERE StuNo='00000025'?t ? ? ? ??諴萀0 17240671.14.2.sql ?螶USE Xk GO EXEC sp_lock GO USE Xk SET DEADLOCK_PRIORITY LOW BEGIN TRANSACTION --事务,系统自动为Student表StuNo='0000001'的数据行加锁 UPDATE Student SET Pwd='1111111' WHERE StuNo='00000001' GO USE Xk GO --事务,系统自动为Course表CouNo='002'的数据行加锁 UPDATE Course SET Credit=4 WHERE CouNo='002' GO SET LOCK_TIMEOUT 1800 /*将锁超时时限设置为1800毫秒*/ GO SELECT @@LOCK_TIMEOUT GO USE master GO ?t ? ?I吢P橪0 17240671.8-1.sql 痧u--2018年-04月-25日 --检查约束: USE Xk GO ALTER TABLE Student ADD CONSTRAINT CK_StuNo CHECK (StuNo like'[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' AND StuNo<>'00000000') GO --问题[7.14] USE Xk GO ALTER TABLE Student DROP CONSTRAINT CK_StuNo GO ALTER TABLE StuCou ADD CONSTRAINT CK_WillOrder CHECK (WillOrder IN(1,2,3,4,5)) GO USE Xk GO ALTER TABLE StuCou ADD CONSTRAINT DF_StuCou_State GO USE Xk GO --创建名为UnsureDefault的默认值 CREATE DEFAULT UnsureDefault AS'待定' GO --将默认值UnsureDefault 绑定到 Course表的 Teacher列上 EXEC sp_bindefault,'Course.Teacher' GO --创建book表 USE Xk GO CREATE TABLE book ( bookID int IDENTITY(1,1), bookName varchar(30) NOT NULL ) GO --输入行数据,只输入BookName列值,标识列bookID由系统自动生成 INSERT book(bookName) VALUES('计算机网络技术') INSERT book(BookName) VALUES('软件测试技术') INSERT book(BookName) VALUES('动态WEB技术') GO --显示book表信息 SELECT * FROM book GO 暐t ? 6 6 洰澥P汱0 17240671.8.2.sql 安淣USE Xk GO CREATE UNIQUE INDEX IX_CouName ON Course (CouName) GO --2,将Student表的IX_StuName引重命名为IX_StuNameNew USE Xk GO EXEC sp_rename 'Student.IX_StuName','IX StuNameNew' GO --3,删除Course表上名字为IX_CouName的索引。 USE Xk GO DROP INDEX Course.IX_CouName GO --4,在Xk数据的Student表上查询姓“林”学生的信息,并分析哪些索引被系统采用。 USE Xk GO SET SHOWPLAN_ALL ON; GO SELECT StuNo,StuName FROM Student WHERE StuName LIKE '林%' GO SET SHOWPLAN_ALL OFF; GO --5,在Xk数据库的Student表上查询学号为“00000001”的学生信息,并分析哪些索引被系统采用。 USE Xk GO SET SHOWPLAN_ALL ON; GO SELECT StuNo FROM Student WHERE StuNo='00000001' GO SET SHOWPLAN_ALL OFF; GO --6,在Xk数据库的Student表上查询姓名为“林斌”的学生信息,并分析执行该数据查询所花费的磁盘活动量信息。 USE Xk GO SET STATISICS IO ON GO SELECT * FROM Student WHERE StuName='林斌' GO SET STATISICS IO OFF GO --7,使用UPDATE STATISTICS语句更新Xk数据库的Student表的PK_Student索引的统计信息。 USE Xk GO UPDATE STATISTICS Student PK_Student GO ?{ @ 课后实训

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值