Skip to content
Advertisement

Unable to assign value to variable with convert

DECLARE @ID VARCHAR(10)='',@I INT=0,@RAND_ CHAR(1)

WHILE @I<10
BEGIN
    SET @RAND_=CONVERT(CHAR,FLOOR(RAND()*10))
    SET @ID+=@RAND_
    SET @I+=1
END
SELECT @ID

If i make it like that it returns me a 10 digit number, but if i try it like that

DECLARE @ID VARCHAR(20)='',@I INT=0

WHILE @I<10
BEGIN
    SET @ID+=CONVERT(CHAR,FLOOR(RAND()*10))
    SET @I+=1
END
SELECT @ID

it returns only 1 digit.Why,isn’t it the same thing?

Advertisement

Answer

In this line:

SET @ID += CONVERT(CHAR, FLOOR(RAND()*10))

The length is not being specified. The default length is 30, and char will pad the rest of the length with spaces. So @ID is already filled, and therefore cannot be added to.

This is fully documented online:

When n isn’t specified in a data definition or variable declaration statement, the default length is 1. If n isn’t specified when using the CAST and CONVERT functions, the default length is 30.

Had you specified the length, or used varchar, this would not have happened.

SET @ID += CONVERT(CHAR(1), FLOOR(RAND()*10))

Always specify char and varchar lengths explicitly

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement