T-SQL编程基础-基本语法
1.局部變量
聲明單個局部變量
declare @num int
聲明多個局部變量
??????????????? @LastName?nvarchar(20)
??????????????? @Age??int
局部變量賦值
被賦值的局部變量必須是已經聲明的。
a.簡單賦值方法
set?@UserName?=?'Niyo?Wong'
b.使用select語句賦值
delcare?@NoOfRecords?intset?@NoOfRecords?=?(select?count(*)?from?tableName)
select?@NoOfRecords?=?20
declare?@UserName??varchar(20)
declare?@UserId??varchar(10)
select?@UserName?=?userName?from?tbl_User?where?userId?=?'123401'
select?@UserId?=?max(UserId)?from?tbl_User
注意:如果查詢返回了多個值時,那么只有最后一個值賦給了變量。
c.使用update語句賦值
update?tableName?set?@qty?=?fieldName?where?id?=?'1'
注意:update無法象select語句一樣魏數據提供一些常用的轉換,所以在使用update進行賦值時,
最好嚴格匹配數據類型,否則會產生錯誤。
2.全局變量
下面列舉幾個我們在編程中常用的全局變量
a. @@CURSOR_ROWS
返回本次服務器連接中,打開游標取回的數據行的數目。如:
declare?employee_cursor?cursor?for
select?emplid?from?tbl_Employee
open?employee_cursor
fetch?next?from?employee_cursor
select?@@CURSOR_ROWS
close?employee_cursor
deallocate?employee_cursor
b. @@ERROR
返回上一條語句返回的錯誤號,執行成功返回0,
一般在insert,update,delete語句之后使用(常結合事務處理)。
c. @@FETCH_STATUS
返回上一次使用游標FETCH操作所返回的狀態值。返回值為0表示操作成功,
為-1表示操作失敗或者已經超過了游標所能操作的數據行的范圍,當到了最后一行數據后,
還要接著取下一列數據,返回-2,表示返回值已經丟失。
d. @@ROWSCOUNT
返回上一條SQL語句所影響到的數據行的數據。常用于檢查操作是否達到了目的,
當執行的SQL語句不影響數據庫數據時,該變量返回0
e. @@VERSION
返回版本號
3.結構語句
a.條件結構
if.... else ...如:
begin
?declare?@num?int
?set?@num?=?(select?max(no)?from?tabl2)
?if(@num?>(select?count(*)?from?table1))
?begin
??print?'@num?>(select?count(*)?from?table1)'
?end
?else
??if(@num?=?(select?count(*)?from?table1))
??begin
???print?'@num?=?(select?count(*)?from?table1)'
??end
end
else
begin
?print?'No?of?record?below?zero'
end
b.循環結構
while 語句。如:
set?@count?=?0
while(@count?<?10)
begin
?print?@count
?set?@count?=?@count?+?1?
end
在循環中常用的語句有break和continue,
break為跳出while,而continue為跳出當前循環,進入下一循環。
有時候也用到return和goto語句,下面我們將講這兩個語句。
c.case語句
case語句又叫條件分支語句。如:
?when?'1'?then?'admin'?
?when?'2'?then?'general?user'?
?else?'other'?end?'userType'?
from?tbl_user
或者
select?'userType'?=?case
??when?USERiD?=?'1'?then?'admin'
??when?userName?=?'Lucy'?then?'admin'
??when?userType?=?'1'?then?'admin'
??when?userType?=?'2'?then?'general?user'
??else?'other'?end
from?tbl_user
注意:case語句中when匹配成功后,就到end,不會匹配下一個when,
所以如果有一條記錄,userid = '1' 并且usertype = '2',
則返回uertype是‘admin'而不是’general user'
d.return語句
立即退出程序,return后面的語句將不執行。return 后常跟一個整形表達式作為返回值。
e.goto語句
跳轉到跟在goto后面的標簽位置。如
???????????? ?@value?int
set?@count?=?(select?count(*)?from?table)
if(@count?=?0)
begin
????set?@value?=?0
????goto?Flag
end
set?@value?=?@count?+?10
Flag:
print?@value
以后將相繼推出觸發器,存儲過程,游標及性能優化
轉載于:https://www.cnblogs.com/Niyowong/archive/2007/08/20/862169.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的T-SQL编程基础-基本语法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网络协议栈11:Connect函数分解之
- 下一篇: 搭建mongodb分片