T-SQL语言

一、T-SQL的语言的组成部分

  1. 数据定义语言(DDL):用于在数据库系统中对数据库、表、视图、索引等数据库对象进行创建和管理

  2. 数据控制语言(DCL):用与实现对数据库中数据的完整性、安全性等的控制

  3. 数据操纵语言(DML):用于插入、查询、修改和删除数据库中的数据

二、局部变量

  1. 声明局部变量

declare @name char(10)

  1. 局部变量赋值

  2. select方式

declare @name char(20)
select @name = name from User where id = 1
print @name
  1. set方式
declare @name char(20),@age int
set @name = '张三',@age = 20

三、全局变量

全局变量是SQL Server系统内部事先定义好的变量,不需要用户参与定义、对于用户而言,其作用范围并不局限于某一程序,而是任何程序随时可以调用。全局变量通常用于存储一些SQL Server的配置设定值和效能统计数据。全局变量都是以‘@@’开头的

四、流程控制

流程控制语句是用来控制程序执行流程的语句。

  1. Begin...End

begin...end语句用于将多个T-SQL语句组合为一个逻辑块。当流程控制语句必须执行一个包含两条或两条以上的T-SQL语句的语句块时,使用Begin...End语句

declare @x int,@y int,@z int
set @x = 1
set @y = 2
begin
set @z=@x
set @x=@y
set @y=@z
end
print @x
print @y
print @z
  1. IF...ELSE
declare @x int.@y int
set @x = 3
set @y = 1
if @x > @y
print '@x>@y'
else
print '@x<@y'
  1. CASE

使用case语句可以很方便地实现多长选择的情况,比IF...THEN结构有更多的选择和判断的机会,从而可以避免编写多重的IF...THEN嵌套循环

  1. 简单case函数
case input_expression
  when when_expression Then result_expression
    [..n]
  [
    else else_result_expression
  end
  1. case搜索函数
case
  When Boolean_expression Then result_expression
    [...n]
  [
    else else_expression
  end
  1. case函数参数表

case 函数的参数及说明

  1. case简单函数和case搜索函数两种格式的执行顺序
  • 简单case函数
  1. 计算 input_expression ,然后按指定顺序对每个When子句的input_expression = when_expression进行计算

  2. 如果input_expression = when_expression 为true,则返回result_expression.

  3. 如果没有取值为true的input_expression = when_expression,则当指定else子句时,SQL Server将返回else_result_expression;若没有指定else子句,则返回null值

  • case搜索函数
  1. 按指定顺序为每个When 子句的Boolean_expression求值

  2. 返回第一个取值为TRUE的Boolean_expression的result_expression

  3. 如果没有取值为True的Boolean_expression,则当指定else子句时,SQL Server将返回else_result_expression;若没有指定else子句,则返回null值

  • 例如:
select *,
备注 = case
when grade >= 90 then '成绩优秀'
when grade < 90 and grade >= 80 then '成绩良好'
when grade < 80 and grade >= 60 then '成绩及格'
else '不及格'
end 
from tb_grade
  1. While

while子句时T-SQL语句支持的循环操作。在条件为真的情况下,while子句可以循环地执行其后的一条T-SQL命令。如果想循环执行一组命令,则需要配合Begin...End子句使用。

declare @n int,@sum int
set @n = 1
set @sum = 0
while @n<=10
begin
set @sum = @sum +@n
set @n = @n + 1
end
print @sum
  1. While...Continue...Break

循环结构while子句还可以用continue和break命令控制while循环中语句的执行。

declare @x int,@sum int
set @x = 1
set @sum = 0
while @x <10
begin
set @x = @x+1
if @x%2=0
set @sum = @sum + @x
else
continue
end
print @sum
  1. Return

return语句用于从查询或过程中无条件退出。

declare @x int
set @x = 3
if @x > 0
print 'before return'
return
print 'after return'
  1. Goto

goto命令用来改变程序执行的流程,使程序跳到标识符指定的程序行再继续往下执行

declare @x int
select @x = 1
loving: 
  print @x
  select @x = @x + 1
while @x<= 3 goto loving
  1. waitfor

waitfor指定触发器、存储过程或事物执行的时间、时间间隔或时间;还可以用来暂时停止程序的执行,直到所设定的等待时间已过才继续往下执行

waitfor delay '00:00:03'
print 'hello world' 
waitfor time '10:34:00'
print 'hello world' 
posted @ 2021-02-25 14:29  阿斯蒂芬芬蒂斯阿  阅读(571)  评论(0)    收藏  举报