SQL数据库-TSQL语法实例介绍
注:下面的例子可以直接运行
1.局部变量,当前程序使用
@开头
use LtsDatabase --打开数据库
declare @test1 int, @test2 char(60) --定义变量,多个之间逗号隔开
select @test1 = 1, @test2 = 'chengzhi',--同时定义多个,逗号隔开
select @test1, @test2 --同时输出多个,逗号隔开
set @test = 100 --只对一个赋值
Print @test --只输出一个
2.全局变量,系统内部使用
@@开头
3.注释
多行注释
/*
这是一个注释
*/
单行注释
–这是一个注释
4.运算符
<>也不等于的意思
5.流程控制
Begin --程序块开始
declare @test1 int, @test2 varchar(60) --定义变量
select @test1 = 200, @test2 = 'chengzhi'--变量赋值
if @test1 = 200 --if test1等于200
print @test2 --输出test2
end
--程序块结束
6.复杂if
Begin --代码块开始
declare @test1 int, @test2 varchar(60), @test3 varchar(60), @test4 varchar(60) --定义四个变量
select @test1 = 90, @test2 = '及格', @test3 = '不及格', @test4 = '优秀' --给四个变量赋值
if @test1 > 0 and @test1 < 60 --0-60分的判断
print @test3 --输出不及格
else if @test1 < 80 --60-80分的判断
print @test2 --输出及格
else --其他情况
print @test4 --输出优秀
end --程序块结束
7.case语句
Begin --开始代码块
declare @test1 int, @test2 varchar(60) -- 定义变量
set @test1 = 92 --赋值变量
--下面的格式要记住
set @test2 = --设置变量的值为case的返回值
case --case语句
--逻辑代码,不要忘记加上then
when @test1 >= 90 and @test1 <= 100 then 'you xiu'
when @test1 >= 80 and @test1 < 90 then 'liang hao'
when @test1 >= 60 and @test1 < 80 then 'ji ge'
end --结束
select 'All = ' + @test2 --输出语句
end -- 结束代码块
8.while语句
declare @test1 int, @test2 int --定义变量
select @test1 = 0, @test2 = 0 --赋值
while @test1 <= 200 --while循环
begin --代码块开始
set @test2 = @test2 + @test1
set @test1 = @test1 + 1
end--结束代码块
print @test2 --输出结果
9.break
declare @test1 int, @test2 int --定义变量
select @test1 = 0, @test2 = 0 --赋值
while @test1 <= 200 --while循环
begin --代码块开始
set @test2 = @test2 + @test1
if @test1 = 30
break --跳出循环
set @test1 = @test1 + 1
end--结束代码块
print @test2 --输出结果
10.continue
declare @test1 int, @test2 int --定义变量
select @test1 = 0, @test2 = 0 --赋值
while @test1 < 200 --while循环
begin --代码块开始
set @test1 = @test1 + 1
if @test1 = 100 --@test1等于100
continue --结束本次循环,下面的代码不会执行,只跳出一次循环
set @test2 = @test2 + @test1
end--结束代码块
print @test2 --输出结果
11.goto测试
print 'goto'
goto test_Target --跳转到标记,中间的代码不执行
print 'no goto'
test_Target: --做一个标记
print 'chengzhi'
测试2
declare @test1 int, @test2 int --定义变量
select @test1 = 0, @test2 = 0 --赋值
test_Target:
set @test1 = @test1 + 1
set @test2 = @test2 + @test1
while @test1 < 200 goto test_Target --小于200,跳转到标记
print @test2