sqlserver 变量级基本语法

--1.变量分为局部变量和全局变量
--局部变量:
--局部变量必须以标记@作为前缀 ,如@age
--局部变量的使用也是先声明,再赋值 
--全局变量:
--全局变量必须以标记@ @作为前缀,如@@version
--全局变量由系统定义和维护,我们只能读取,不能修改全局变量的值 
--2.局部变量
--1>声明
declare @name varchar(8)
declare @age int
--2>赋值
set @name='jack' --赋值方式一
set @age=20
select @name=firstname from employees
where employeeid=1 --赋值方式二
--3>使用 输出
--convert(数据类型,表达式):将表达式转成指定数据类型
print '姓名:'+@name+',年龄:'+convert(varchar,@age) --以消息形式输出
select @name as '姓名'--以表格形式输出
go

--3.全局变量
--@@ERROR:最后一个T-SQL错误的错误号,如果为0无错
--@@IDENTITY:最后一次插入的标识值
--@@ROWCOUNT:受上一个SQL语句影响的行数
select * from employees
select * from employees where employeeid=1
print '总共查询到'+convert(varchar,@@rowcount)

update employees set birthdate='2011-1-1' where employeeid=1
print '错误代号'+convert(varchar,@@error)
go
--4.if
--格式: if <条件> begin 语句序列  end 
--      else     begin 语句序列 end
--:说明:当语句序列只有一句时,begin end可省略
--根据产品的名称,输出对应价格等级
declare @price money
declare @pname varchar(10)
set @pname='Chai'
select @price=unitprice from products
where productname=@pname
if @price>50
   print ''
else if @price>30
   print '一般'
else 
   print '便宜'
go
--5.case end
--格式:CASE 
--  WHEN 条件1 THEN  结果1
--  WHEN 条件2 THEN  结果2
--  ……
--  ELSE 其他结果
--END
declare @week int
declare @weekStr varchar(6)
set @week=2--星期一
set @weekStr= case
                when @week=1 then '星期一'
                when @week=2 then '星期二'
                when @week=3 then '星期三'
                else '星期天'
              end
print @weekStr
go

select productid,productname,unitprice,
  case 
     when unitprice>50 then ''
     when unitprice>30 then '一般'
     else '便宜'
  end
 as '等级' 
from products
go

--6.while循环
--格式:WHILE <条件>
--  BEGIN
--    语句1
--    语句2
--    ……
--    BREAK
--  END
declare @i int
set @i=1
while @i<=10
begin
   print @i
   if @i=5
      break;
   set @i=@i+1
end
go

--为了本次考试更好,进行一定的提分,
--确保每人的总分都达到200分以上,提分规则很简单,
--先给每人加2分,看是否都通过,如果没有全部通过,
--每人再加2分,再看是否达到200分,如此反复提分,直到所有人都通过为止。
declare @i int --记录加的次数
declare @price money
set @i=0
while
begin
    select @price=min(unitprice) from products 
    if @price>=30
       break
    update products set unitprice=unitprice+2
    set @i=@i+1
end
go

declare @i int --记录加的次数
set @i=0
while 1=1
begin
    if not exists(select * from products where unitprice<30)
        break
    update products set unitprice=unitprice+2
    set @i=@i+1
end
go
原文地址:https://www.cnblogs.com/kite/p/3635577.html