一、 定義游標
使用游標相當於c#裡面的集合。
declare@idnvarchar(20)
declare my_cursor cursor
--定義游標
for (select autoid from u_voucheritems where cardnum=
'k006
'and cardsection='b
') --
查出需要的集合放到游標中
open my_cursor; --
開啟游標
fetch
next
from my_cursor into
@id; --
讀取第一行資料
while
@@fetch_status=0
begin
update u_voucheritems set carditemnum=(select
max(carditemnum)+
1from u_voucheritems where cardnum=
'k006
'and cardsection='b
') where cardnum=
'k006
'and autoid=
@idfetch
next
from my_cursor into
@id; --
讀取第一行資料
endclose my_cursor; --
關閉游標
deallocate my_cursor; --
釋放游標
二、觸發器和游標一起使用
例子
/****** object: trigger [dbo].[tgr_changeprice_delete] script date: 03/25/2016 11:33:41 *****
*/set ansi_nulls on
goset quoted_identifier on
gocreate
trigger
[dbo
].[tgr_changeprice_delete]on
[dbo
].[sa_saledelivery_b
]instead
ofdelete
asdeclare
@s_jsquantity
nvarchar(100),@zquantity
nvarchar(100),@s_wjsquantity
nvarchar(100),
@clearingmoney
nvarchar(100),@yxquantity
nvarchar(100),@notclearingmoney
nvarchar(100),
@price
nvarchar(100),@changepricedetailerid
nvarchar(100); --
定義變數
declare my_cursor cursor
--定義游標
for (select quantity2,quantity,origdiscountprice,sourcevoucherdetailid from deleted) --
查出需要的集合放到游標中
open my_cursor; --
開啟游標
fetch
next
from my_cursor into
@zquantity,@s_jsquantity,@price,@changepricedetailerid; --
讀取第一行資料
if(@changepricedetailerid
isnot
null) --
判斷begin
'start......
'while
@@fetch_status=0
begin
set@s_wjsquantity
=convert (decimal(19,2),@s_jsquantity
);
set@clearingmoney
=convert (decimal(19,2),@price)*
convert (decimal(19,2),@s_jsquantity
);
set@notclearingmoney
=convert (decimal(19,2),@price)*
convert (decimal(19,2),@s_wjsquantity
);
update nsc_changeprice_b set
yxquantity
= yxquantity+
convert (decimal(19,2),@s_jsquantity
), jsquantity
=jsquantity-
convert (decimal(19,2),@s_jsquantity
), wjsquantity
=wjsquantity+
convert (decimal(19,2),@s_wjsquantity
), clearingmoney
=clearingmoney-
convert (decimal(19,2),@clearingmoney
), notclearingmoney
=notclearingmoney+
convert (decimal(19,2),@notclearingmoney
)
where id=
@changepricedetailerid
fetch
next
from my_cursor into
@zquantity,@s_jsquantity,@price,@changepricedetailerid; --
讀取第一行資料
endclose my_cursor; --
關閉游標
deallocate my_cursor; --
釋放游標
endelse
begin
'end.....'--
rollback transaction --回滾﹐避免加入
end
sql service 儲存過程,游標的使用
1 建表 drop table dbo.users gocreate table dbo.users id int not null name varchar 32 null go alter table dbo.users add primary key id go2 新增資料 刪除儲存過程 if...
觸發器和游標
1 觸發器 觸發時自動生成兩個表inserted和deleted 定義 類似於c 中的事件,是一種特殊的引數不用手動呼叫 語法 create trigger 觸發器名 on設定觸發器的表 after for 或 instead of 查詢語句型別 insert,delete,updata asbeg...
觸發器和游標
1 觸發器 觸發時自動生成兩個表inserted和deleted 定義 類似於c 中的事件,是一種特殊的引數不用手動呼叫 語法 create trigger 觸發器名 on設定觸發器的表 after for 或 instead of 查詢語句型別 insert,delete,updata asbeg...