小编典典

在SQL Server中正确修剪二进制数据

sql

设想:

我正在将字符串插入二进制字段(CONTEXT_INFO),然后稍后尝试将其拉出并将其转换回字符串。当我这样做时,结果字符串的长度为128,因为它具有结尾的空字符。

例子:

DECLARE @string VARCHAR(128)
DECLARE @binary VARBINARY(128)

SET @string = 'abcdefg'
SET @binary = CONVERT(VARBINARY(128), @string) --0x61626364656667000000...
SET CONTEXT_INFO @binary
SET @binary = CONTEXT_INFO()

-- I would like to change the following line so it trims trailing null chars
SET @string = CONVERT(VARCHAR(128), @binary)

SELECT
    @binary AS [binary],
    DATALENGTH(@binary) AS [binary.Length], --128 as expected
    @string AS [string],
    DATALENGTH(@string) AS [string.Length] --This is 128, but I need it to be 7

问题:

将二进制字段转换为字符串时,如何修剪尾随的空字符?


阅读 215

收藏
2021-05-23

共1个答案

小编典典

试试这个,works on Sql-Server 2008.这是Sql
Fiddle

请注意,我假设原始字符串中未包含Char(0),因为即使从原始字符串中也可以简单地替换它。

-- I would like to change the following line so it trims trailing null chars
SET @string = CONVERT(VARCHAR(128), @binary)
SET @string = REPLACE(@string, Char(0),'')
2021-05-23