創建存儲過程
create procedure 存儲過程名 @參數名1 數據類型1 [=default] [out | output | readonly]
as
...sql語句...
go
執行存儲過程
execute 存儲過程名 參數1
刪除存儲過程名
drop procedure 存儲過程名
修改存儲過程
alter procedure 存儲過程名 @參數名1 數據類型1 [=default] [out | output | readonly]
as
...sql語句...
go
l 索引
創建索引
create [unique] [clustered | nonclustered] index 索引名
on 表名 (列名[,列名]...) [with fillfactor = x]
其中:
unique 表示將要創建唯一索引,唯一索引不允許兩行具有相同的索引值
clustered表示將要創建聚集索引 或 nonclustered 表示將要創建非聚集
聚集索引在速度上比非聚集索引快,因爲聚集索引中行的物理順序與索引鍵值的邏輯順序是一致的,但一個表中最多只能有一個聚集索引,可以有一個或多個非聚集索引
with fillfactor = x:表示填充因子,取值在0~100間的值,該值表示索引頁填滿的空間所佔用的百分比,指定合適的填充因子可以提高數據改動時的執行效率
刪除索引
drop index 索引名
常用的有:if exists (select * from sysindexes where name = 索引名) drop index 索引名
l 變量的使用
定義變量:
declare 變量名(必須以@開頭) 數據類型
給變量賦值:
set 變量名 = 表達式
select 變量名=表達式 from 表或視圖 ...
一般來說,簡單賦值(比如賦給此變量一個常量)使用set,複雜的賦值(比如需要在表或視圖中查詢數據時)使用select
3個常用的全局變量:
@@error 最後一個T-SQL錯誤的錯誤號
@@identity 最後一次作插入操作時的標識列的值
@@rowcount 受上一個SQL語句影響的行數
l case多分支語句
case when 條件1 then 結果1
when 條件2 then 結果2
[else 其它結果]
end
l 子查詢
select * from 表1 where 列1 { = | <> | != | > | >= | !> | < | <= | !< } [all | some | any](子查詢)
some與any是等效的,相當於當前列1 的值與子查詢的所有結果進行比較滿足條件的至少有一個,相當於||運算
all與以上的相反,相當於&&運算
l 表聯接查詢
內聯接:
select * from 表1 inner join 表2 on 條件
左外聯:
select * from 表1 left outer join 表2 on 條件
右外聯:
select * from 表1 right outer join 表2 on 條件
完全外聯:
select * from 表1 full outer join 表2 on 條件
自聯接:
select * from 表1 別名1 [inner | left outer | right outer | full outer] join 表1 別名2 on 條件(使用別名1和別名2)