动态 sql 和上下文信息中的错误字符串

bad string in dynamic sql and context info

这太奇怪了!下面的代码是一个t-sql.

BEGIN
    DECLARE @cinfo VARBINARY(128) = CAST('aud:83/53784862/1' AS VARBINARY(128));
    DECLARE @csinfo VARCHAR(128) = CAST(CONTEXT_INFO() AS VARCHAR(128));
    SET @csinfo = '<root><value>' + REPLACE(RIGHT(@cinfo, LEN(@cinfo) - 4), '/', '</value><value>') + '</value></root>';
    PRINT @csinfo
    SET CONTEXT_INFO @cinfo;
    DECLARE @sql VARCHAR(MAX) = '
        DECLARE @cinfo VARCHAR(128) = CAST(CONTEXT_INFO() AS VARCHAR(128));
        DECLARE @csinfo VARCHAR(512) = ''<root><value>'' + REPLACE(RIGHT(@cinfo, LEN(@cinfo) - 4), ''/'', ''</value><value>'') + ''</value></root>'';
        PRINT @csinfo
    '
    EXEC(@sql)
END

这是输出:

<root><value>83</value><value>53784862</value><value>1</value></root>
<root><value>83</value><value>53784862</value><value>1

为什么没有附加</value></root>

我找到了解决方案。

DECLARE @cinfo VARCHAR(128) = REPLACE(CAST(CAST(CONTEXT_INFO() AS VARCHAR(128)) COLLATE SQL_Latin1_General_CP1_CI_AS AS VARCHAR(128)), CHAR(0), '');

这将修复从 CONTEXT_INFO() 转换而来的字符串。