-- 0、 Sql server中的代码块
/*
类似于各种开发语言,sql server也具有代码块的分割,大部分语言代码块用大括号分割({})*/
begin
end
--用于sql server数据库中的代码分割
-- 一、 变量的定义、赋值、输出
declare @a int--定义变量
set @a=5 --变量赋值
print @a --打印变量的值
--使用select语句赋值
--select既可以用于变量赋值也可以用于输出变量,当输出变量用时跟我们查询语句中的相同
declare @user1 nvarchar(50)
select @user1='张三'--定义变量
select @user1--输出变量
-- 二、 表、临时表、表变量
--创建临时表
create table #DU_User1
(
[ID] [int] NOT NULL,
[Oid] [int] NOT NULL,
);
--向临时表插入记录
insert into #DU_User1 (ID,Oid) values (100,2);
--定义表变量
declare @t table
(
id int not null,
msg nvarchar(50) null
) ;
--向表变量插入记录
insert into @t table (ID,msg ) values (100,'123');
-- 三、 循环 while循环求1到100的和 (sql server中只有while循环)
declare @a int
declare @sum int
set @a=1
set @sum=0
while @a<=100
begin
set @sum+=@a
set @a+=1
end
select @sum
-- 四、条件语句
--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