sqlserver2008 T_SQL篇

事物

事物的概念:--转自百度百科
事务(Transaction)是并发控制的单位,是用户定义的一个操作序列。这些操作要么都做,要么都不做,是一个不可分割的工作单位。通过事务,SQL Server能将逻辑相关的一组操作绑定在一起,以便服务器保持数据的完整性。
事务通常是以BEGIN TRANSACTION开始,以COMMIT或ROLLBACK结束。
COMMIT表示提交,即提交事务的所有操作。具体地说就是将事务中所有对数据库的更新写回到磁盘上的物理数据库中去,事务正常结束。
ROLLBACK表示回滚,即在事务运行的过程中发生了某种故障,事务不能继续进行,系统将事务中对数据库的所有以完成的操作全部撤消,滚回到事务开始的状态。
事务的特性(ACID特性)
A:原子性(Atomicity)
事务是数据库的逻辑工作单位,事务中包括的诸操作要么全做,要么全不做。
B:一致性(Consistency)
事务执行的结果必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。
C:隔离性(Isolation)
一个事务的执行不能被其他事务干扰。
D:持续性/永久性(Durability)
一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。

例:

select * from paihangbang

begin try ---设立开始点

begin tran

索引:

索引的概念:
索引使数据库应用程序可以更快地查找数据。
创建普通索引:
CREATE INDEX index_name
ON table_name (column_name)
创建唯一索引:
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
删除索引:
drop INDEX INDEX_name on 表名(列名)
显示索引:
SHOW INDEX from 表名

游标:
提供了对查询结果集进行逐行处理的方式
declare ll_cursor cursor for select * from students
2.打开游标
open ll_cursor
3.依次往下读取结果集中的每一行数据
/****** Script for SelectTopNRows command from SSMS ******/
SELECT TOP 1000 [id]
,[son]
,[name]
,[sex]
,[age]
FROM [SchoolIDB].[dbo].[students]

declare @id int
declare @son nvarchar
declare @name nvarchar
declare @sex nvarchar
declare @age int
declare ll_cursor cursor for select * from students
open ll_cursor

fetch next from ll_cursor into @id,@son,@name,@sex,@age
print @id
print @son
print @name
print @sex
print @age
close ll_cursor //关闭游标
deallocate ll_cursor //释放资源

//注意:
Cursorfetch: INTO 列表中声明的变量数目必须与所选列的数目相同。必须与列名的数量相同 //id,name..等

游标的原理:通过在结果集中设立的一个指针来从上往下一行行遍历数据的一个过程

注意:
//在遍历完成后,需要关闭游标 并且释放掉资源

2.可以通过访问@@fetch_status 全局变量的值来判断当前是否读取到数据航
如果@@fetch_studet=0 说明读取成功
否则就是读取失败

存储过程:
预先编译好一段sql语句,用来实现特定得功能,类似c#中的方法
定义存储过程的语法
go
create procedure usp_过程名
as
sql语句
....
存储过程的命名规范:usp_功能
例:
GO
CREATE PROCEDURE PR_Sum
@a int,
@b int,
@sum int output

AS
BEGIN
set @sum=@a+@b
END

调用存储过程:
execute 存储过程名
存储过程也分有参和无参
--调用、执行存储过程
exec proc_get_student; //在不同的地方调而不是在本程序调用

3、 修改存储过程

--修改存储过程
alter proc proc_get_student
as
select * from student;

4、 带参存储过程

--带参存储过程
if (object_id('proc_find_stu', 'P') is not null)
drop proc proc_find_stu
go
create proc proc_find_stu(@startId int, @endId int)
as
select * from student where id between @startId and @endId
go

exec proc_find_stu 2, 4;

5、 带通配符参数存储过程

--带通配符参数存储过程
if (object_id('proc_findStudentByName', 'P') is not null)
drop proc proc_findStudentByName
go
create proc proc_findStudentByName(@name varchar(20) = '%j%', @nextName varchar(20) = '%')
as
select * from student where name like @name and name like @nextName;
go

exec proc_findStudentByName;
exec proc_findStudentByName '%o%', 't%';

6、 带输出参数存储过程

if (object_id('proc_getStudentRecord', 'P') is not null)
drop proc proc_getStudentRecord
go
create proc proc_getStudentRecord(
@id int, --默认输入参数
@name varchar(20) out, --输出参数
@age varchar(20) output--输入输出参数
)
as
select @name = name, @age = age from student where id = @id and sex = @age;
go

--
declare @id int,
@name varchar(20),
@temp varchar(20);
set @id = 7;
set @temp = 1;
exec proc_getStudentRecord @id, @name out, @temp output;
select @name, @temp;
print @name + '#' + @temp;


7、 不缓存存储过程

--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 student;
go

exec proc_temp;

8、 加密存储过程

--加密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 student;
go

exec proc_temp_encryption;
exec sp_helptext 'proc_temp';
exec sp_helptext 'proc_temp_encryption';

9、 带游标参数存储过程

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, name, age from student;
open @cur;
go
--调用
declare @exec_cur cursor;
declare @id int,
@name varchar(20),
@age int;
exec proc_cursor @cur = @exec_cur output;--调用存储过程
fetch next from @exec_cur into @id, @name, @age;
while (@@fetch_status = 0)
begin
fetch next from @exec_cur into @id, @name, @age;
print 'id: ' + convert(varchar, @id) + ', name: ' + @name + ', age: ' + convert(char, @age);
end
close @exec_cur;
deallocate @exec_cur;--删除游标


10、 分页存储过程

---存储过程、row_number完成分页
if (object_id('pro_page', 'P') is not null)
drop proc proc_cursor
go
create proc pro_page
@startIndex int,
@endIndex int
as
select count(*) from product
;
select * from (
select row_number() over(order by pid) as rowId, * from product
) temp
where temp.rowId between @startIndex and @endIndex
go
--drop proc pro_page
exec pro_page 1, 4
--
--分页存储过程
if (object_id('pro_page', 'P') is not null)
drop proc pro_stu
go
create procedure pro_stu(
@pageIndex int,
@pageSize int
)
as
declare @startRow int, @endRow int
set @startRow = (@pageIndex - 1) * @pageSize +1
set @endRow = @startRow + @pageSize -1
select * from (
select *, row_number() over (order by id asc) as number from student
) t
where t.number between @startRow and @endRow;

exec pro_stu 2, 2;


? Raiserror

Raiserror返回用户定义的错误信息,可以指定严重级别,设置系统变量记录所发生的错误。

语法如下:

Raiserror({msg_id | msg_str | @local_variable}
{, severity, state}
[,argument[,…n]]
[with option[,…n]]
)

# msg_id:在sysmessages系统表中指定的用户定义错误信息

# msg_str:用户定义的信息,信息最大长度在2047个字符。

# severity:用户定义与该消息关联的严重级别。当使用msg_id引发使用sp_addmessage创建的用户定义消息时,raiserror上指定严重性将覆盖sp_addmessage中定义的严重性。

任何用户可以指定0-18直接的严重级别。只有sysadmin固定服务器角色常用或具有alter trace权限的用户才能指定19-25直接的严重级别。19-25之间的安全级别需要使用with log选项。

# state:介于1至127直接的任何整数。State默认值是1。

raiserror('is error', 16, 1);
select * from sys.messages;
--使用sysmessages中定义的消息
raiserror(33003, 16, 1);
raiserror(33006, 16, 1);


--创建触发器
Create trigger User_OnUpdate
On ST_User
for Update
As
declare @msg nvarchar(50)
--@msg记录修改情况
select @msg = N'姓名从“' + Deleted.Name + N'”修改为“' + Inserted.Name + '”' from Inserted,Deleted
--插入日志表
insert into [LOG](MSG)values(@msg)

--删除触发器
drop trigger User_OnUpdate

原文地址:https://www.cnblogs.com/liyiyong1994/p/9119518.html