Reputation: 31
How can I add 5596 + 00003 to get 559600003 in SQL Server?
I tried with the following query:
select 5596 + '00003'
But it is giving 5599 and I want this to show 559600003.
Upvotes: 2
Views: 107
Reputation: 196
You can use CAST
SELECT CAST(5596 AS varchar) + '00003'; -- return 559600003
Because :
But in case you have a date type CONVERT is more flexible and contains more options than CAST
For more details take a look : https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?redirectedfrom=MSDN&view=sql-server-ver15
Upvotes: 2
Reputation: 27289
SQL Server attempts to return the result in the datatype of the first part of the calculation which in your case is a number. It can happily convert the second part of the calculation into a number, and therefore does so.
To obtain the result you want you must convert the first part of the calculation to a string e.g.
select convert(varchar, 5596) + '00003'
Note: convert(varchar,x)
uses a default length of 30 which is probably enough for most numbers.
CONCAT()
, as in one of the other answers is probably a better solution.
Upvotes: 5
Reputation: 50163
You can also use CONCAT()
:
SELECT CONCAT(5596, '00003')
CONCAT()
does not require any explicit conversion.
Upvotes: 8