1

here is the code to re-produce the issue:

DECLARE @VBIN BINARY(50)
DECLARE @PASS NVARCHAR(3)
DECLARE @TEXT NVARCHAR(MAX)

SET @TEXT = '123456123789'
SET @PASS = '123'
SET @VBIN = CONVERT(BINARY, N'321')
SELECT REPLACE(@TEXT, @PASS,  CONVERT(NVARCHAR(MAX), @VBIN))

would return '321' insetead of '321456321789'

1 Answer 1

1

The issue is that binary(50) will pad with 0x00 to reach the fixed length of 50 and that is generally treated as a string terminator.

You see the same behaviour with

SELECT N'The quick brown ' +  NCHAR(0) + N' fox jumped over the lazy dog.'

The data is actually still there after the REPLACE. It is in the attempt to display it as a string that truncation occurs.

DECLARE @VBIN BINARY(50)
DECLARE @PASS NVARCHAR(3)
DECLARE @TEXT NVARCHAR(MAX)

SET @TEXT = '123456123789'
SET @PASS = '123'
SET @VBIN = CONVERT(BINARY, N'321')

SELECT REPLACE(@TEXT, @PASS,  CONVERT(NVARCHAR(MAX), @VBIN))
SELECT DATALENGTH(REPLACE(@TEXT, @PASS,  CONVERT(NVARCHAR(MAX), @VBIN))) /*112*/

SELECT CAST(REPLACE(@TEXT, @PASS,  CONVERT(NVARCHAR(MAX), @VBIN)) AS VARBINARY(112))

Using varbinary rather than binary would avoid the issue but I'm not sure what you are actually trying to do here anyway.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks Martin, in your answer "SELECT N'The quick brown ' + NCHAR(0) + N' fox jumped over the lazy dog.'" led me to the right direction, for the solution i used a function from another post (stackoverflow.com/questions/15259622/…) to remove non ascii charachters form the string and now string does not terminates and i do get the desired output '321456321789'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.