Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right Trimming Binary Data in SQL Server

Scenario:

I am inserting a string into a binary field (CONTEXT_INFO) and then later attempting to pull it out and convert it back to a string. When I do, the resulting string has a length of 128 because it has trailing null characters.

Example:

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

Question:

How can I trim the trailing null characters when I convert the binary field to a string?

like image 877
Dan Avatar asked Jan 04 '13 18:01

Dan


People also ask

How do you trim a right space in SQL?

SQL Server TRIM() FunctionThe TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string. Note: Also look at the LTRIM() and RTRIM() functions.

How do I fix string or binary data would be truncated in SQL Server?

To fix this error, patch to SQL Server 2016 SP2, CU6 or newer (including SQL Server 2017), and then turn on trace flag 460. You can enable it at the query level or at the server level.

How will you avoid string or binary data would be truncated in SQL?

Solution. To avoid this error and to insert the string with truncation, use the ANSI_WARNINGS option. On setting ANSI_WARNINGS to OFF, the error message will not be displayed and the data will be automatically truncated to the length of the destination column and inserted.

How do you trim both sides in SQL?

The SQL function trim(both from …) removes space characters from the end (right side) of a string. The keywords both from are optional. The result of the example is the text 'traveling space' with the spaces removed from both ends.


1 Answers

Try this, works on Sql-Server 2008. Here is Sql Fiddle.

Please note that I am assuming that the original string has NOT got Char(0) in it as this could simply replace it even from the original string.

-- 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),'') 
like image 189
Kaf Avatar answered Sep 18 '22 05:09

Kaf