1. 程式人生 > >資料庫學習SQLServer第四章 T-SQL語句

資料庫學習SQLServer第四章 T-SQL語句

T-SQL語句是標準SQL語句的增強版,原有的SQL語句是一種結構化查詢語言

4.1.語句分類

1.變數宣告語句
2.DDL—資料定義語言(CREATE,ALTER,DROP,DECLARE)
3.DML—資料操縱語言(SELECT,DELETE,UPDATE,INSERT)
4.DCL—資料控制語言(GRANT,REVOKE,COMMIT,ROLLBACK)
5.流程控制語句
6.內嵌函式與自定義函式
SQLServer 一般作為後臺資料庫,配合其他高階語言,開發出各種資料庫應用程式

4.2變數的宣告與複製

1.宣告語句

declare @變數名 int(變數型別)宣告變數語句這是一個區域性變數,以@開頭


set @變數名=值 給變數賦值
select @變數名 用select顯示變數的值

2.區域性變數和全域性變數

1.區域性變數必須用@開頭
2.用declare宣告,也可以宣告多個變數,格式為@變數名 型別,@變數名 型別;中間用逗號隔開
3.set是單一一個變數賦值
select 是同時為多個變數賦值
4.輸出
如果輸出一個變數用print
輸出多個變數用select

3.運算子

大神的總結
Francis
微控制器控制挖掘機炒菜不是夢

程式塊概念
將一部分程式碼以begin開始,end結束
例項
–SQL的while迴圈,注意資料型別的轉換

declare @num1 int,@sum int
select @num1=0,@sum=0
while @num1<=200
begin
set @
[email protected]
[email protected] set @[email protected]+1 end select '200以內的整數和是'+convert(varchar(10),@sum)' --這裡加號相當於字串連線符,需要更改其資料型別

break語句的位置不同,計算的結果就不同,程式設計時靈活運用的技巧

declare @num1 int,@sum int
select @num1=0,@sum=0
while @num1<=200
begin
set @[email protected][email protected]
if @num1=30 --計算前30位的和 break set @[email protected]+1 end select '以內的整數和是'+convert(varchar(10),@sum)
declare @num1 int,@sum int
select @num1=0,@sum=0
while @num1<=200
begin
set @[email protected][email protected]
set @[email protected]+1
if  @num1=30             --計算前29位的和
break
end
select '以內的整數和是'+convert(varchar(10),@sum)

continue 語句

declare @num1 int,@sum int
select @num1=0,@sum=0
while @num1<=200
begin
set @[email protected][email protected] 
if  @num1=100     --當等於100時,continue跳出迴圈,
continue              --計算200以內的整數和,但不包括10
set @[email protected]+1           
end
select '運算結果0'+convert(varchar(10),@sum)

最大的區別在於break一出現跳出整個迴圈,之後語句不再執行,整個迴圈中斷。
continue一出現,只跳出這一輪迴圈,跳出後繼續執行while
具體可參考別人總結的小例項
while break continue

4.go to 語句改變程式流程,實現位置跳轉。

Goto語句可以讓程式跳轉到一個指定的標籤處並執行其後的程式碼。Goto語句和標籤可以在程式批處理和語句塊中的任意位置使用,也可以巢狀使用。

--要實現顯示第一行後直接顯示第三行
print 'Goto語句測試'
goto test_Target
print'當前無Goto跳轉'
test_Target:
print'我是教程'   --Goto直接跳轉到test_Target:標籤位置

goto語句學習及使用注意事項
(https://www.cnblogs.com/ylbtech/archive/2012/12/25/2832112.html)

declare @num1 int,@sum int
select @num1=0,@sum=0
test_target:
    set @[email protected]+1
	set @[email protected][email protected]
    while @num1<200 goto test_target    
select '200以內的整數和是'+convert(varchar(10),@sum)

用if獲while判斷,是否跳轉執行test_target標籤