SQL Server嵌套游标丢失内层游标首行问题排查与解决
嵌套游标内层丢失首行问题排查与解决
我参考微软T-SQL游标相关文档实现了嵌套游标,但内层游标总是丢失首行,请问是不是在实现过程中遗漏了文档里的内容?
以下是用于排查的查询代码:
DECLARE @client_id VARCHAR(50); DECLARE @reportID INT; DECLARE @report_name VARCHAR(250); DECLARE @client_report_id INT; DECLARE @pdf_file_format VARCHAR(200) = ''; DECLARE @expected_file_format VARCHAR(200) = 'somevalue'; DECLARE @export_file_name VARCHAR(200) = ''; IF OBJECT_ID('tempdb..#client_reports') IS NOT NULL DROP TABLE #client_reports; --创建临时表存储客户端报表数据 SELECT cr.client_report_id, cr.client_id, c.name 'client_name',r.report_id, r.name 'report_name' ,r.report_code, c.export_file_name, cr.pdf_file_format INTO #client_reports FROM t004_client_report cr JOIN t002_report r ON r.report_id = cr.report_id JOIN t001_client c ON cr.client_id = c.client_id WHERE r.name LIKE ('FilterText%') DECLARE cursor_ReportName CURSOR FOR SELECT distinct report_id, report_name FROM #client_reports; OPEN cursor_ReportName FETCH NEXT FROM cursor_ReportName INTO @reportID, @report_name WHILE @@FETCH_STATUS = 0 BEGIN PRINT '------------------' PRINT 'Processing report: ' + @report_name PRINT '------------------' DECLARE cursor_ClientReport CURSOR FOR SELECT client_id, client_report_id, export_file_name, pdf_file_format FROM #client_reports WHERE report_id = @reportID OPEN cursor_ClientReport FETCH NEXT FROM cursor_ClientReport INTO @client_id, @client_report_id, @export_file_name, @pdf_file_format WHILE @@FETCH_STATUS = 0 BEGIN --部分行因问题未被处理 --在此编写客户端报表pdf格式的更新代码 IF @pdf_file_format <> @expected_file_format BEGIN PRINT @client_id + ': updating pdf_file_format from: ' + @pdf_file_format + ' to ' + @expected_file_format --更新逻辑代码 END FETCH NEXT FROM cursor_ClientReport INTO @client_id, @client_report_id, @export_file_name, @pdf_file_format END CLOSE cursor_ClientReport--关闭并释放游标 DEALLOCATE cursor_ClientReport --获取下一个报表 FETCH NEXT FROM cursor_ReportName INTO @reportID, @report_name END CLOSE cursor_ReportName;--关闭并释放游标 DEALLOCATE cursor_ReportName; IF OBJECT_ID('tempdb..#client_reports') IS NOT NULL DROP TABLE #client_reports;
问题原因与解决
经排查,问题出在pdf_file_format列存在NULL值。SQL中NULL与任何值进行<>(不等于)比较时结果都是NULL,不会进入IF分支,同时会导致逻辑异常,表现为首行丢失。
修改方案:在判断条件中用ISNULL函数处理NULL值,将NULL转换为空字符串后再比较,修改后的判断语句为:
IF ISNULL(@pdf_file_format, '') <> @expected_file_format
修改后代码运行正常。
内容的提问来源于stack exchange,提问作者Niranjan Singh
相关产品推荐
相关产品推荐

