第三章SQL编程

一、使用变量

    什么是变量:变量是可以存储数据值的对象

    1.局部变量

        语法:

DECLARE @variable_name DateType
SET @variable_name=value

         如:

DECLARE @name nvarchar(50)
SET @name='张三'

      set语句与select语句的区别

  set select
同时对多个变量赋值 不支持 支持
表达式返回多个值时 出错 将返回的最后一个值赋给变量
表达式未返回值时 变量值被赋为null 变量保持原值

 

2.全局变量

@@error(重点) 最后一个T-SQL错误的错误号
@@identity 最后一次插入的标识列
@@rowcount 受上一个SQL语句语句影响的行数
@@servername 本地服务器的名称
@@version

SQL Server的版本信息

二、输出语句

       常用的输出语句有两种,即print语句和select语句,语法如下:

print 局部变量或字符串


select 局部变量 as 自定义列名

         其中,使用select语句输出数据是查询语句的特殊应用

         例题:

use MySchool
--学号是23270李小龙姓名和年龄
select studentName as 姓名,datediff(YY,birthday,GETDATE())  as 年龄 from Student where StudentNo=23270

declare @age int 
select @age=datediff(YY,birthday,GETDATE()) 
from Student
where StudentNo=23270 
print @age
--比李小龙年龄小的人的姓名和年龄
select studentName as 姓名,datediff(YY,birthday,GETDATE())  as 年龄 from Student
where datediff(yy,birthday,Getdate())<@age

--比李小龙年龄大的人的姓名和年龄
select studentName as 姓名,datediff(YY,birthday,GETDATE())  as 年龄 from Student
where DATEDIFF(YY,birthday,GETDATE())>@age

--比李小龙年龄小一岁的人的信息
select * from Student
where DATEDIFF(YY,birthday,GETDATE())=@age-1

--比李小龙年龄大一岁的人的信息
select * from Student
where DATEDIFF(YY,birthday,GETDATE())=@age+1

三、数据类型转换

         1.cast()和convert()函数

                     语法:

cast ( 表达式  as  数据类型 )

convert ( 数据类型[(长度)] , 表达式[,样式] )

          上机练习1:

declare @i int
set @i=1

declare @j int
set @j=1

declare @rows nvarchar(50)
set @row=''

while(@i<=5)
begin
    while(@j<=@i)
      begin
         set @str+='*'
         set @j+=1
      end
     print @str
     set @i+=1
end

四、逻辑控制语句

   1.begin-end语句(作用类似于C#中的大括号)

       语法:

begin
   语句或语句块
end

   2.if-else条件语句

      语法:(跟begin-end语句连用)

if(条件)
   begin
      语句1
      语句2
       ......
   end
else
       ......

   3.while循环语句

     语法:

while(条件)
   begin
       语句或语句块
       [break|continue]
   end

  4.case多分支语句

     语法:

case 
   when  条件1  then  结果1
   when  条件2  then  结果2
   [else 其他结果]
end
原文地址:https://www.cnblogs.com/hr1997/p/5248021.html