一.注釋
-- 單行注釋,從這到本行結束為注釋sql 語法,類似c++,c#中//
多行注釋,類似c++,c#中
二.變數(int, smallint, tinyint, decimal,float,real, money ,smallmoneysql 語法, text ,image, char, varchar。。。。。。)
語法:declare
} [,...n]
例如:declare @id int --申明乙個名為@id的變數,型別為int型
三.在sql server視窗中列印出變數的值
語法:print 'any ascii text' | @local_variable | @@function | string_expr
四.變數賦值
例如:--從資料表中取出第一行資料的id,賦值給變數@id,然後列印出來
declare @id int
set @id = (select top(1) categoryid from categories)
print @id
在sql中,我們不能像**那樣直接給變數賦值,例如@id = 1,如果要達到這樣的功能,可以這樣寫:
declare @id int
set @id = (select 1) -- 類似 @id=1
select @id=1 -- 類似 @id=1
print @id
五.變數運算(+,-,*sql 語法,/,……)
以下必要時候省略變數申明
set @id = (select 1+5) --類似 @id=1+5
set @id=(select 1-@id) --類似 @id=1-@id
六.比較操作符
? >(greater than).
? <(less than).
? = (equals).
? <= (less than or equal to).
? >= (greater than or equal to).
? != (not equal to).
? <>(not equal to).
? !< (not less than).
? !> (not greater than).
沒什麼說的
七.語句塊:begin … end
將多條語句作為乙個塊,類似與c++,c#中的
例如:begin
set @id1 = (select 1)
set @id2 = (select 2)
end八.if, if…else…
語法:if boolean_expression_r
[else
]例如:
if @id is not null
print 『@id is not null
if @id = 1
begin
set @id = (select 1 + 1)
endelse
begin
set @id=(select 1+2)
end上面的例子用到了比較操作符,語句塊,和if的語法。
九.執行其他儲存過程 exec
例如exec dbo.[sales by year] @beginning_date=』1/01/90』, @ending_date=』1/01/08』
十.事務
語法:begin tran[saction] [transaction_name | @tran_name_variable]
例如begin tran
-- 做某些操作,例如insert into …
if @@error <>0
begin
rollback tran
endelse
begin
commit tran
end十一.游標
我們可以在儲存過程中用select語句取出每一行資料進行操作,這就需要用到游標。
語法:declare cursor_name cursor
[local | global]
[forward_only | scroll]
[static | keyset | dynamic | fast_forward]
[read_only | scroll_locks | optimistic]
[type_warning]
for select_statement
[for update [of column_name [,...n]]]
例如:declare @au_id varchar(11), @au_fname varchar(20) –申明變數
--申明乙個游標
declare authors_cursor cursor for
select au_id, au_fname from authors
--開啟游標
open authors_cursor
--取出值
fetch next from authors_cursor into @au_id, @au_fname
--迴圈取出游標的值
while @@fetch_status = 0
begin
print @au_id
print @au_fname
print 『 』
fetch next from authors_cursor
into @au_id, @au_fname
endclose authors_cursor –關閉游標
deallocate authors_cursor --釋放游標
mysql 儲存過程及游標使用,
因為資料表的資料量太大,每天定時執行分表的儲存過程,時間長了分表數量過多,需要定期刪除分表,先建立儲存過程,之後設定定時事件去執行儲存過程 create procedure sp droptables begin declare t name varchar 64 declare isfinishe...
oracle儲存過程及游標使用例項
create or replace procedure t table count test as v tablename varchar2 50 v count integer str sql varchar2 200 從all tables裡面獲取的所有表的表名稱,儲存在游標內 cursor m...
mysql 游標及儲存過程游標的使用 源自技術
乙個完整的mysql游標使用例子 定義本地變數 declare o varchar 128 定義游標 declare ordernumbers cursor for select callee name from account tbl where acct timeduration 10800 d...