1

I want to generate some integers in SQL Server loop and add it to end of string that is a long number

Declare @i int
Set @i = 10

While @i < 45
Begin
    insert into AllowedStudents (GroupID, StudentNumber) 
    values ('1', '9210410' + @i)

    SET @i = @i + 1
End

but when insert process ends I see this result :

28240   1   9210420
28241   1   9210421
28242   1   9210422
28243   1   9210423

against

28240   1   921041020
28241   1   921041021
28242   1   921041022
28243   1   921041023

2 Answers 2

3

Convert @i from int to varchar

Like this

insert into AllowedStudents (GroupID, StudentNumber) 
values ('1', '9210410' + Convert(varchar(50), @i))

SQLFIDDLE

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

Comments

0

This is because of type precedence in SQL Server. Int datatype has higher precedence than varchar datatype, causing varchar to be implicitly converted to int type. You need to explicitly convert your int variable to varchar datatype.

This can be done with cast or convert functions:

'9210410' + cast(@i as varchar(100))

or

'9210410' + convert(varchar(100), @i)

For more information on datatype precedence visit https://msdn.microsoft.com/en-us/library/ms190309.aspx

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.