--- mssql
begin try
if not cursor_status('global','c_cur')=-3 and not cursor_status('local','c_cur')=-3 -- 存在时候销毁游标
begin
close c_cur;
deallocate c_cur;
end
declare
c_cur cursor for select id from XXX;
declare @v_id nvarchar(50)
begin
open c_cur;
fetch from c_cur into @v_id;
while @@fetch_status=0
begin
if cursor_status('global','c_cur')=-3 and cursor_status('local','c_cur')=-3
begin
print '不存在'
end
else
begin
print '存在'
end
declare @V_SQL varchar(max),@TABLENAME varchar(30);
set @TABLENAME = 'T1'
SET @V_SQL=N'select top 10 * from '+ @TABLENAME+' TD WHERE id='+@v_id+';';
EXEC SP_EXECUTESQL @V_SQL
fetch from c_cur into @v_ID;
loop:
end;
close c_cur;
deallocate c_cur;
end;
end try
BEGIN CATCH
-- ROLLBACK TRANSACTION -- 始终回滚事务
-- DECLARE @ErrorMessage NVARCHAR(4000) ;
DECLARE @ErrorSeverity INT ;
DECLARE @ErrorState INT ;
SELECT @ErrorMessage = ERROR_MESSAGE() ,
@ErrorSeverity = ERROR_SEVERITY() ,
@ErrorState = ERROR_STATE() ;
PRINT @ErrorMessage
INSERT INTO t_err_Log (errmsg,otime) VALUES ( @ErrorMessage, getdate());
RAISERROR(@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
) ;
RETURN -1 ;
END CATCH
-- oracle 当然可以使用简化的for循环
V_ErrMsg VARCHAR2(1000); ----保存异常信息
declare
cursor emp_cur is select * from emp;
empRecord emp%rowtype;
begin
open emp_cur;
loop
fetch emp_cur into empRecord;
exit when emp_cur%notfound;
dbms_output.put_line(empRecord.ename);
end loop;
close emp_cur;
end;
EXCEPTION -- 异常情况
WHEN OTHERS THEN
rollback;
V_Err := 'XXX 报错! ' || TO_CHAR(SQLCODE) || ': ' ||
SQLERRM || 'vDataType:' || vDataType;
INSERT INTO t_err_Log (errmsg,otime) VALUES( V_ErrMsg, SYSDATE);
commit;
raise_application_error('-20001', V_Err);
-- mysql
declare v_d datetime;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION,SQLWARNING set _error=1;
declare no_more_times,_error integer default 0; -- 定义游标遍历时,作为判断是否遍历完全部记录的标记
declare c_cur cursor for select now(); -- 定义游标
declare continue handler for not found set no_more_times=1; -- 遍历完之后值
start transaction;
open c_cur;
repeat
fetch c_cur into v_datetime;
-- 放开可以避免有一个重复
-- if no_more_times<>1 then
loop;
set @s=concat("select now(),'",v_datetime,"';")
prepare s from @s;
execute s;
until no_more_times end repeat; -- 结束循环
close c_cur;
IF _error=0 THEN
COMMIT;
else
ROLLBACK;
end if