2

Code bellow is not working, any ideas why?

declare @Counter int
set @Counter = 0
declare @ConcText nvarchar(1000)

while @Counter < 5
begin
    --set @ConcText = @ConcText + cast(@Counter as nvarchar(10)) + N' counter,'
    --set @ConcText = @ConcText + convert(nvarchar(10), @Counter) + N' counter,'
    set @ConcText = @ConcText + N' counter,'
    set @Counter = @Counter + 1
end
print @ConcText --<-- this is null, why  ??
1
  • Define "not working" What is is spitting out. What should it be spitting out? Commented Mar 5, 2009 at 14:51

2 Answers 2

7

See MSDN: + (String Concatenation) (Transact-SQL):

Just like arithmetic operations that are performed on null values, when a null value is added to a known value the result is typically an unknown value, a string concatenation operation that is performed with a null value should also produce a null result.

So to get things work, it's a good practice to initiate varchar variables immediatly after declare:

DECLARE @ConcText NVARCHAR(1000)
SET @ConcText  = ''

Other way to handle NULL concat issue (in case you don't know if value is NULL or not) - ISNULL or COALESCE:

SET @ConcText = ISNULL(@ConcText, '') + N' counter,'
SET @ConcText = COALESCE(@ConcText, '') + N' counter,'
Sign up to request clarification or add additional context in comments.

Comments

4

You are not setting @ConcText to anything at the start, therefore when you concatenate anything to NULL you get NULL.

Comments

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.