Why does the @result value in the code below print out a blank string? I would expect it to concatenate with the previous result.
DECLARE @size int
DECLARE @string nvarchar(10)
DECLARE @result nvarchar(10)
SELECT @string = '12345abc123'
DECLARE @count int, @total int
SELECT
@total = LEN(@string),
@count = 1
WHILE @count <= @total
BEGIN
SELECT @result = SUBSTRING(@string, @count, 1) + '-'+ @result
SELECT @count = @count + 1
PRINT @result
END
You never initialized @result, so it defaults to an sql null. SQL nulls are contagious poison, so when you do
SELECT @result = .... + @result
You're actually doing
SELECT @result = ... + null
and @result simply remains null
Initializing the value to an empty string solves your problem:
SET @result = ''
It is returning a blank because you are concatenating the substring with @result, which initially is NULL.
Try setting @result to an empty string like this this:
SELECT @string = '12345abc123', @result = ''
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With