Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this TSql return a blank or null value?

Tags:

sql

t-sql

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
like image 874
John S Avatar asked Jan 19 '26 14:01

John S


2 Answers

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 = ''
like image 127
Marc B Avatar answered Jan 21 '26 05:01

Marc B


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 = ''
like image 24
MDiesel Avatar answered Jan 21 '26 06:01

MDiesel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!