sql-server - 如何在长结果查询中处理try_cast错误

标签 sql-server error-handling try-cast

我试图弄清楚如何捕获错误,并找出try_cast之一何时返回null。我在存储过程中的查询如下所示:

   SELECT
          try_cast(ORI.body AS xml).value('(/BODY/@formid)[1]', 'INT') AS 'Form ID'
        , try_cast(ORI.body AS xml).value('(/BODY/@form_answers)[1]', 'NVARCHAR(MAX)') AS 'Body'
        , ORN.info_id
        , getdate() as create_date
    FROM
        ORG_NOTEPAD ORN
    INNER JOIN
        ORG_INFO ORI ON ORN.info_id = ORI.id
    WHERE 
        COALESCE(ORI.template_id,0)<>0 
    AND 
        COALESCE(ORN.case_id,0)<> 0 
    AND 
        ORN.type_id <> 4
该查询返回大约800行。在此有3个单独的尝试广播。
我知道每个try_cast都可以返回null,但是其中任何一个也可以返回错误消息。如何运行此查询,但还能找到任何返回null或错误消息的try_cast结果?我需要获取结果中包含null或错误消息的内容的详细信息,例如info_id和form id,并将错误信息和上下文写入错误表。但是我还将把“好”结果写到一个单独的表中。
我发现了很多examples of things that will cause an error,但是在此,我需要捕获更多有关null或错误消息的信息。我找到的最接近的东西是this stored procedure example,但是在将信息应用于示例时遇到了麻烦。
我不确定是否需要将case语句和一个临时表与单个try_cast一起使用,还是关于错误处理/null/良好答案处理。
我对存储过程以及try_cast等还比较陌生。感谢您的帮助。

最佳答案

create table #ORG_INFO
(
id int identity(1,1),
body nvarchar(max)
);

insert into #ORG_INFO(body)
values
(N'<BODY formid="1234"/>'),
(NULL), --just null
(N'<BODY>'), --invalid xml
(N'<BODY formid="abcd"/>'), --formid not a number
(N'<BODY anotherattrib="1234"/>'); --missing @formid

select 
case 
    when body is null then cast('body is null' as varchar(100))
    when try_cast(body as xml) is null then 'invalid xml'
    when try_cast(body as xml).exist('/BODY/@formid') = 0 then 'missing formid'
    when try_cast(body as xml).exist('xs:integer((/BODY/@formid)[1])') = 0 then 'non-numeric formid'
    else 'ok'   
end as ctrlmsg,
try_cast(body as xml).value('xs:integer((/BODY/@formid)[1])', 'int') as formid,
*
from #ORG_INFO;


drop table #ORG_INFO;

关于sql-server - 如何在长结果查询中处理try_cast错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63677699/

相关文章:

python - 为什么通过从另一个模块调用函数来显示来自不同模块中不同 GUI 的图像时会出现问题?

php - PHP MYSQL中的错误跟踪-是否有更多信息?

带有allowCustomSqlDatabase ="true"的ASP.NET SessionState不调用指定的数据库

sql-server - 报告服务仅显示最后一行

SQL Server 的 C# 日期格式

sql - 有没有办法计算列中 NULL 之间的非空数量?

python-3.x - KeyError 中错误消息的新行 - Python 3.3