>[1]局部變量
declare @name varchar(8)-----name為變量名,varchar為數據類型
局部變量賦值:
1. set @name = value
2. select @name = value
declare @name varchar(8)
……………………………………………………………………………………………………………………………………
set @name = 李文才
select * from stuinfo where stuname = @name
declare @seat int
set @seat = stuseat from stuinfo where stuname = @name
select * from stuinfo where (stuseat = @seat+1) or (stuseat = @seat-1)
go
>[2]全局變量
@@error 最後一個T-SQL錯誤的錯誤號
@@identity 最後一次插入的標識列
@@language 當前使用的語言的名稱
@@max_connections 可以創建的同時連接的最大數目
@@rowcount 受上一個SQL語句影響的行數
@@servername 本地服務器的名稱
@@servicename 該計算機上的SQL服務的名稱
@@timeticks 當前計算機上每刻度的微妙數
@@transcount 當前連接打開的事物數
@@version SQL Server的版本信息
……………………………………………………………………………………………………………………………………
>[3] if-else 條件語句
if(條件)
begin
語句1
語句2
……
end
else
……
declare @myavg float
set @myavg = avg(writtenexam) from stumarks
print 平均分+convert(varchar(5),@myavg)
if(@myavg>70)
begin
print 本班筆試成績優秀,前三名的成績為:
select top 3 * form stumarks order by writtenexam desc
end
else
begin
print 本班筆試成績較差,後三名的成績為:
select top 3 * from stumarks order by writtenexam
end
……………………………………………………………………………………………………………………………………
>[4] while 循環語句
declare @n int
while(1=1)-----條件永遠成立
begin
set @n = count(*) from stumarks where writtenexam<60
if(@n>0)
update stumarks set writtenexam = writtenexam+2
else
break
end
print 加分後的成績為:
select * from stumarks
……………………………………………………………………………………………………………………………………
>[5] case 多分支語句
case
when 條件1 then 結果1
when 條件2 then 結果2
………
else
end
select * form stumarks
select stuno,成績 = case
when writtenexam<60 then e
when writtenexam between 60 and 69 then d
when writtenexam between 70 and 79 then c
when writtenexam between 80 and 89 then b
else a
end
from stumarks