设想: + J8 S& q8 { e6 J我正在将字符串插入二进制字段(CONTEXT_INFO),然后试着把它拉出来,转换回字符串。当我这样做时,字符串的长度是128,因为它有结尾的空字符。/ ~3 ^) O6 P( ?' ^* t9 p 例子: ' q$ L) ]. i; g3 UDECLARE @string VARCHAR(128)DECLARE @binary VARBINARY(128)SET @string = 'abcdefg'SET @binary = CONVERT(VARBINARY(128),@string) --0x61626364656667000000...SET CONTEXT_INFO @binarySET @binary = CONTEXT_INFO()-- I would like to change the following line so it trims trailing null charsSET @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问题: # J4 }( f) c5 a0 N; l2 K. k: k9 P将二进制字段转换为字符串时,如何修剪跟随的空字符? 6 O$ H, n! y4 T+ V7 R# e4 s c( g0 J 4 F* c: v1 K/ @解决方案: . R6 j. D& }, `+ v
试试这个,works on Sql-Server 2008.这是Sql 1 B5 t$ q+ y) Y3 d9 R E- F. ?# ~Fiddle。; P3 ^, W/ I# R; X: R
请注意,我假设原始字符串不包括在内Char(0),因为它可以简单地从原始字符串中替换。1 n0 O! ?6 C/ h& @* c u
-- I would like to change the following line so it trims trailing null charsSET @string = CONVERT(VARCHAR(128),@binary)SET @string = REPLACE(@string,Char(0)