技术开发 频道

SQL Server数据库编程基本语法汇总

  四、条件语句

  --if,else条件分支

  
if(1+1=2)

  
begin

  
print ''

  
end

  
else

  
begin

  
print ''

  
end

  
--when then条件分支

  
declare @today int

  
declare @week nvarchar(3)

  
set @today=3

  
set @week=case

  
when @today=1 then '星期一'

  
when @today=2 then '星期二'

  
when @today=3 then '星期三'

  
when @today=4 then '星期四'

  
when @today=5 then '星期五'

  
when @today=6 then '星期六'

  
when @today=7 then '星期日'

  
else '值错误'

  
end

  
print @week

  五、游标

  declare @ID int

  
declare @Oid int

  
declare @Login varchar(50)

  
--定义一个游标

  
declare user_cur cursor for select ID,Oid,[Login] from ST_User

  
--打开游标

  
open user_cur

  
while @@fetch_status=0

  
begin

  
--读取游标

  
fetch next from user_cur into @ID,@Oid,@Login

  
print @ID

  
--print @Login

  
end

  
close user_cur

  
--摧毁游标

  
deallocate user_cur

  六、触发器

  触发器中的临时表:

  Inserted

  存放进行insert和update 操作后的数据

  Deleted

  存放进行delete 和update操作前的数据

  --创建触发器

  
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

  七、存储过程

  --创建带output参数的存储过程

  
CREATE PROCEDURE PR_Sum

  
@a int,

  
@b int,

  
@sum int output

  
AS

  
BEGIN

  
set @sum=@a+@b

  
END


  
--创建Return返回值存储过程

  
CREATE PROCEDURE PR_Sum2

  
@a int,

  
@b int

  
AS

  
BEGIN

  
Return @a+@b

  
END


  
--执行存储过程获取output型返回值

  
declare @mysum int

  
execute PR_Sum 1,2,@mysum output

  
print @mysum


  
--执行存储过程获取Return型返回值

  
declare @mysum2 int

  
execute @mysum2= PR_Sum2 1,2

  
print @mysum2
0
相关文章