在TSQl中使用变量,事务,系统存储,自定义存储

--1、声明变量
    declare @name varchar(20)
    declare @age int
    --2、赋值
    --(1)
    set @age=18
    set @name='yqq'
    --(2)
    select @age=18
    select @name='yqq'
   
    --3分别使用set和select 为行号变量@rcount赋值
    declare @rcount int
    set @rcount=(select COUNT (*) from T_Student)   
    print @rcount
    select @rcount= COUNT (*) from T_Student      
    -----计算T_Score表中FEnglish平均成绩  如果>=60 查询正数前三名 否则找出倒数前三名-------
 declare @count int
 select @count=COUNT(*) from  T_Score
 declare @sum float
 select @sum=SUM(FEnglish) from T_Score
 declare @avg float
 select @avg=(@sum/@count)
 if @avg>60
 begin
 select top 3 * from T_Score
 order by FEnglish desc
 end
 else
 begin
 select * from T_Score
 order by FEnglish desc
 end--4通过while 计算1---100之间奇数的和。
 declare @sum2 int =0
 declare @i int =1
 
 while @i<=100
   begin
      if @i%2<>0
     begin
      set @sum2=@sum2+@i
     end
     set @i=@i+1
   end
   print @sum2
 
--5通过while 计算1---100之间偶数的和。
declare @sum3 int =0
declare @j int =1
while @j<=100
  begin
     if @j%2=0
     begin
      set @sum3=@sum3+@j
     end
     set @j=@j+1
  end
  print @sum3
--6使用while实现如果english不及格的人超过半数,则给每个人增加2分,循环加,直到不及格的人数少于一半。
declare @count2 int =(select COUNT(*)from T_Score)
declare @loster int =(select COUNT(*) from T_Score where FEnglish<60)
  declare @harfcount int=floor(@count2/2)
  while @harfcount<@loster
    begin
       update T_Score set FEnglish=FEnglish+2 where FEnglish<60
       set @loster=(select COUNT(*)from T_Score where FEnglish<60)
    end
--7使用事务实现--转账问题:从0001账户转1000块到0002账户。
 create table Bank
 (
   Cid char(4) primary key,
   balance money
 )
 alter table Bank
 add constraint CH_balance check (balance>=10)

 insert into Bank values('0001',1000)
 insert into Bank values('0002',10)
 
 begin tran
 begin try
 declare @errorSum int =0
 update Bank set balance=balance-1000 where Cid='0001'
 set @errorSum=@errorSum+@@error
 update Bank set balance=balance+1000 where Cid='0002'
 set @errorSum=@errorSum+@@error
 commit
 print '提交!!'
 end try
 begin catch
    rollback
    print '回滚!'
 end catch
--8打开"隐式事务":设置为开,删除表中数据,回滚!(默认情况为关,如果打开了则不自动提交,学要手动提交)
 set implicit_Transactions on     --打开
 delete from Bank
 rollback
 
--9关闭“隐式事务”。
----如果隐式事务打开,然后删除某个表,在事务没有结束前,其它查询不能访问该表。
    set implicit_Transactions off  --关闭
--10使用系统存储过程
--   给数据'Test'重命名为:'Test123'
    exec sp_renamedb 'Test','Test123'
   
--   查询当前数据库中有多少个表
    exec sp_tables
--   查询当前数据库中student表中的列信息
    exec sp_columns 'Student'
--11自定义存储过程 “usp_Helloworld”并使用。实现输出hello world!
    create proc usp_Helloworld
 as
  begin
    print 'hello world!'
  end
 
  exec usp_Helloworld

原文地址:https://www.cnblogs.com/duanlinlin/p/2825923.html