SQLserver--表变量、事务、存储过程

来源:互联网 发布:wap竞猜网站源码 编辑:程序博客网 时间:2024/05/10 02:16

在T—Sql中使用变量
(一)局部变量
--1声明变量  @age和@name
declare  @age int
declare @name nvarchar(5)
--2赋值
----(1)方法1
set @age=18
set @name='张飞'
(2)方法2
select @age=18
select @name='张飞'
--3分别使用set和select 为行号变量@rcount赋值
declare @rcount int
--set @rcount=(select COUNT(*) from TblStudent)
select @rcount=COUNT(*) from TblStudent
print @rcount

select tSAge from TblStudent
declare @Age int
--set @Age=(select tSAge from TblStudent)---出错
select top 5 @Age= tSAge from TblStudent
select @Age

print @@servername

 

通过while 计算1---100之间奇数的和。
declare @sum int =0
declare @ji int =1
while @ji<=100
begin
if @ji%2<>0
begin
set @sum=@sum+@ji
end
set @ji=@ji+1

end
print @sum
通过while 计算1---100之间偶数的和。
declare @sum2 int =0
declare @ou int =0
while @ou<=100
begin
if @ou%2=0
begin
set @sum2=@sum2+@ou
end
set @ou=@ou+1
end
print @sum2

 

事务,就是把一系列操作作为一件事处理,要么都完成,要么都不完成!

--begin transaction--打开事务
begin tran--打开事务
begin try
declare @errorSum int =0
update Bank set balance=balance-900 where Cid='0001'
set @errorSum=@errorSum+@@error
update Bank set balance=balance+900 where Cid='0002'
set @errorSum=@errorSum+@@error
commit
print '提交!!'

end try
begin catch
   rollback
   print '回滚!'
end catch

--if @errorSum=0
--  begin
--  commit tran
--  print '提交!!!'
--  end
--else
--  begin
--  rollback
--  print '回滚!!!'
--  end
 


commit tran--提交事务
rollback tran--回滚事务
-----'自动提交事务':系统检测sql语句是否出错,如果没有错误就自动提交--
insert into Bank values('0003',1000)
--如果希望手动提交,可以回滚在执行插入等操作的时候:
begin tran--打开事务
insert into Bank values('0004',4200000)
rollback--手动回滚或提交事务
--commit
--"隐式事务":默认情况为关,如果打开了则不自动提交,学要手动提交。
set implicit_Transactions on
delete from Bank
rollback
select * from Bank
--如果隐式事务打开,然后删除某个表,在事务没有结束前,其它查询不能访问该表。
--这就是“锁”,由于只是执行了一个sql的操作,没有结束事务,就会把表锁住,不让别人在对他进行操作。放置并发问题出现。
set implicit_Transactions off

 

 

六、存储过程!!
--与C#中的方法一样。存储过程 有 名/可以有参数/可以有返回值。

--6.1系统存储过程
--放在系统数据库 master 中的--可编程性---存储过错--系统存储过程中。

使用 sp_helptext 来显示一个 存储过程 中的 代码 。
exec sp_helptext sp_databases
exec sp_helptext sp_helptext
--给数据库重命名:
exec sp_renamedb 'Test','Test123'
--查询当前数据库中有多少个表
exec sp_tables
--查询当前数据库中的列信息
exec sp_columns 'Student'

自定义存储过程一般是以 usp_开头
create proc usp_Helloworld
as
 begin
   print 'hello world!'
 end