Is it possible to convert a varchar(10) into an int in SQL Server 2014?
I tried the following code, but I get a conversion error
Declare #Random varchar(10)
set #Random = CONVERT(varchar, right(newid(),10))
Declare #rand int = cast(#Random as int)
select #rand
Is it possible to convert a varchar(10) into an int under SQL Server 2012?
Yes, if the varchar(10) string is all numeric characters and the string is within the bound of an int:
-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)
In other words, this will work:
select cast('2147483647' as int)
This will not:
select cast('2147483648' as int)
I tried the following code, but I get a conversion error
The code in your question isn't testing whether you can convert a string to an integer, it is testing whether any random string can be converted. Your random strings contain alpha characters that cannot convert to an integer so you are getting conversion errors. But even if you limit the random string to numbers, you will still only be able to convert numeric strings up to 2147483647 before you overflow your int. I don't think that generating (not-so) random strings that meet this criteria will prove much. The simple answer to your question is yes, you can convert a string to an int, as long as the string meets the requirements of an int.
You could try:
SELECT TRY_CAST(RIGHT(CAST(convert(VARBINARY, NEWID(), 1) AS BIGINT),10) AS INT);
Rextester Demo
Or if you use only 9 digitis:
SELECT RIGHT(CAST(convert(VARBINARY, NEWID(), 1) AS BIGINT),9) + 0;
Related
How come string can contain integer. Even if I assume string storing numeric values as string, but even i can use in it calculation and getting the result as well. Just to try I wrote 5 in inverted commas and still calculation works fine. Not sure how?
declare #x varchar(20)
declare #y int
select #x='5'
select #y=6
select #x+#y
SQL Server -- and all other databases -- convert values among types when the need arises.
In this case, you have + which can be either string concatenation or number addition. Because one argument is an integer, it is interpreted as addition, and SQL Server attempts to convert the string to a number.
If the string cannot be converted, then you will get an error.
I would advise you to do your best to avoid such implicit conversions. Use the correct type when defining values. If you need to store other types in a string, use cast()/convert() . . . or better yet, try_cast()/try_convert():
try_convert(int, #x) + #y
A varchar can contain any character from the collations codepage you are using. For the purposes of this answer, I'm going to assume you're using something like the collation SQL_Latin1_General_CP1_CI_AS (which doesn't have any "international" characters, like Kanji, Hiragana, etc).
You first declare the variable #x as a varchar(20) and put the varchar value '5' in it. This is not an int, it's a varchar. This is an important distinction as a varchar and a numerical data type (like an int) behave very differently. For example '10' has a lower value than '2', where as the opposite is true for 10 and 2. (This is one reason why using the correct data type is always important.)
Then the second variable you have is #y, which is an int and has the value 6.
Then you have your expression SELECT #x+#y;. This has 2 parts to it. Firstly, as you have 2 datatypes, Data Type Precedence comes into play. int has a higher precedence than a varchar, and so #x is implicitly converted to an int. Then the expression is calculated, uses + as an addition operator (not a concatenation operator). Therefore the expression is effectively derived like this:
#x + #y = '5' + 6 = CONVERT(int,'5') + 6 = 5 + 6 = 11
SQL Server uses the following precedence order for data types:
user-defined data types (highest)
sql_variant
xml
datetimeoffset
datetime2
datetime
smalldatetime
date
time
float
real
decimal
money
smallmoney
bigint
int
smallint
tinyint
bit
ntext
text
image
timestamp
uniqueidentifier
nvarchar (including nvarchar(max) )
nchar
varchar (including varchar(max) )
char
varbinary (including varbinary(max) )
binary (lowest)
I have a table with a column of binary literals converted to strings that I need to relate to a table containing the same value as binary(16)
Root table string Value '2F774578C33011E880D80050569C29CA'
table value I need to join to 0x2F774578C33011E880D80050569C29CA
is there a way to convert either the root table to Binary by simply adding the 0x to the string then declaring the string a literal value for the binary? or convert the binary to the string contained in the root.
I tried the following with no luck:
DECLARE #jobIDBinary Binary(16)
DECLARE #jobString Nvarchar(50)
SET #jobIDBinary = '0x'+
(SELECT TOP (1) JobId
FROM [Record])
error: Implicit conversion from data type nvarchar to binary is not allowed. Use the CONVERT function to run this query.
I also tried converting the other way:
DECLARE #convo varchar(max)
SET #convo = (SELECT TOP (1)
[BinaryJobID]
FROM [GAPClaims].[dbo].[Record2]
WHERE binaryjobId IS NOT NULL )
Results = ,]óJ¾¶‡Á§\ê€
Thanks ahead of time.
You can convert your varbinary to varchar, and join on it (or relate it, as you stated).
declare #v varbinary(16) = 0x2F774578C33011E880D80050569C29CA
select #v, convert(varchar(256), #v,2)
declare #s varchar(256) = '2F774578C33011E880D80050569C29CA'
select #s, convert(varbinary(16),#s,2)
So, for you:
DECLARE #convo varchar(max)
SET #convo = (SELECT TOP (1)
convert(varchar(256),[BinaryJobID],2)
FROM [GAPClaims].[dbo].[Record2]
WHERE binaryjobId IS NOT NULL )
See the Binary section in the docs for why I used 2 in the convert statement.
Try this to convert string to binary:
CONVERT(BINARY(16), #jobString)
and Reverse:
CONVERT(VARCHAR(max), #jobBinary)
Why does the following T-SQL statement:
select CAST(COALESCE('3537601039',0) as bigint)
result in the following error when run against MS SQL Server 10?
The conversion of the varchar value '3537601039' overflowed an int
column.
Is there a "more correct" way to do this conversion of a varchar to a bigint that would avoid this problem when the number is within range of a bigint?
The first thing that is happening is that your string is trying to convert to a regular int to match the 0. Try this:
select CAST(COALESCE('3537601039','0') as bigint)
It appears that putting the unqualified zero in the coalesce is implying a conversion to a smaller int before it is explicitly recast to a bigint.
The following simple change to make it a coalesce of string values solves the problem:
select CAST(COALESCE('3537601039','0') as bigint)
Cast first, then do ISNULL
select ISNULL(CAST('3537601039' as bigint), 0)
select ISNULL(NULLIF(ISNULL(CAST('3537601039' as bigint), 0), 0), 1) + 3537601039
sql server firstly discovers isnull(string, numeric) and that numeric zero is by default int. So it tries to convert that string containing bigint to int. You were trying to cast to bigint too late.
another try:
select ISNULL('3537601039', 100000000000)
This question already has an answer here:
Varchar variable is not working in WHERE clause
(1 answer)
Closed 9 years ago.
I'm working with Microsoft SQL Server (2008 R2 if that matters)
When I execute
select LEN('test')
I get 4 as expected
But now try this:
declare #s varchar
set #s='test'
select LEN(#s)
And the result is ... 1
How does it actually work?
That is because if you were to
SELECT #s
it would return
t
only. You need to specify the length.
From char and varchar (Transact-SQL)
When n is not specified in a data definition or variable declaration
statement, the default length is 1. When n is not specified when using
the CAST and CONVERT functions, the default length is 30.
SQL Fiddle DEMO
When you define this:
declare #s varchar
you get a varchar of exactly one character length .
There's absolutely nothing wrong with LEN!
What you need to do is specify an explicit length when you define your varchar variable
declare #s varchar(20)
set #s='test'
select LEN(#s)
Now you should get back 4 from LEN ...
Note: it is a recommend best practice to always specify a length when you use varchar - otherwise you'll run into these kind of surprises. ....
you have to declare it as nvarchar with more than 1 char
try this, it works:
declare #s nvarchar(100)
Recently I was Playing with SQL Server data types, and a Large number of data in the table and trying to figure out the Performance with Varchar and Numeric data. But, I got some error which I don't think should not have been but it is. My problem is below :
I have a table :
create table sa(f1 varchar(100))
I have a Stored Procedure that Inserts 100000 data into the table :
create proc sad
as
begin
declare #i int=0
while #i<100000
begin
insert into sa values(#i)
set #i=#i+1
end
end
exec sad
And I have tested the following:
select CONVERT(int,f1) from sa //Works Fine, i tested after the Problem
select sum(convert(int,f1)) from sa //Didn't Worked, So i tested above and Below
select sum(convert(decimal(18,2),f1)) from sa //And, it again works fine
But, When I sum Converting F1 to Int, it shows me an error.
But, when I only select Converting to Int it's fine.
And, when I sum Converting F1 to decimal it works Fine.
What is the SUM function data type?
On the Above data, it works well with Decimal but not Int?
Why?
I'm Getting the Following error
Arithmetic overflow error converting expression to data type int.
You're summing as INT which has a range that cannot hold that sum.
The DECIMAL can.
The sum of all values from 1 up to 99999 is 4999950000, the maximum INT value is 2147483647, less than half of what the sum ends up as.
When you sum INT's, you're getting a new INT. When you're summing DECIMAL's, you're getting a new DECIMAL, so the input type defines the output type.
You can switch to using bigint instead, and it should "be fine".
Also, on a second note, please don't store numbers as text!
According to MS documentation (see https://learn.microsoft.com/en-us/sql/t-sql/functions/sum-transact-sql), the SUM() function returns values of a different type, according to the datatype of the column you are adding: if the column is of type int, tinyint, or smallint, then SUM returns values of type int.
Converting to bigint or decimal makes SUM() return a larger datatype, this explains why in that case you have no overflow.
Expect you have exceeded the maximum int value that SQL Server allows (2,147,483,647) - see https://learn.microsoft.com/en-us/sql/t-sql/data-types/int-bigint-smallint-and-tinyint-transact-sql.
Decimal allows a far higher limit of up to 10^38 - 1 (i.e. 1 with 38 zeros after) - see https://learn.microsoft.com/en-us/sql/t-sql/data-types/decimal-and-numeric-transact-sql.
However, if the values are of type int, I wouldn't recommend converting to decimal. Decimal values are useful when you have figures with possible numbers after the decimal place with a known precision and scale (e.g. for currency, percentages etc.) As another poster has suggested, the best conversion here would be to a bigint:
select sum(cast(f1 as bigint)) from sa
Looks like your resulting sum is too big for int, use bigint, also check int, bigint, smallint, and tinyint (Transact-SQL)
select sum(convert(bigint,f1)) from sa
Try this:
CONVERT(NUMERIC(18,2),SUM(0))