1. 程式人生 > >記一次sql使用遊標迴圈更新資料

記一次sql使用遊標迴圈更新資料

過程:

ALTER PROCEDURE [dbo].[updateCode]
AS
BEGIN
	-- routine body goes here, e.g.
	-- SELECT 'Navicat for SQL Server'
	declare @gid varchar(50)
, @code varchar(50)
, @pid varchar(50)
--定義一個遊標 
declare user_cur cursor for SELECT ka_product_id  from ka_return_order_line WHERE return_order_no in(SELECT return_order_no FROM ka_return_order_head  where ka_id=181) and bar_code is null
--開啟遊標 
open user_cur
--讀取遊標
fetch next from user_cur into  @pid
while @@fetch_status=0 
begin
-- 定義內層遊標
	DECLARE code_cur  cursor for  SELECT goods_id,barcode  from internationl_barcode
	open code_cur
	fetch next from code_cur into  @gid,@code
	while @@fetch_status=0
	BEGIN
-- 	判斷internationl_barcode裡有的code,然後更新
			if(@
[email protected]
) BEGIN UPDATE ka_return_order_line set [email protected] WHERE [email protected] BREAK END fetch next from code_cur into @gid,@code END close code_cur --摧毀遊標 deallocate code_cur fetch next from user_cur into @pid end close user_cur --摧毀遊標 deallocate user_cur END