Convert a string to int using sql query - sql

How to convert a string to integer using SQL query on SQL Server 2005?

You could use CAST or CONVERT:
SELECT CAST(MyVarcharCol AS INT) FROM Table
SELECT CONVERT(INT, MyVarcharCol) FROM Table

Starting with SQL Server 2012, you could use TRY_PARSE or TRY_CONVERT.
SELECT TRY_PARSE(MyVarcharCol as int)
SELECT TRY_CONVERT(int, MyVarcharCol)

Also be aware that when converting from numeric string ie '56.72' to INT you may come up against a SQL error.
Conversion failed when converting the varchar value '56.72' to data type int.
To get around this just do two converts as follows:
STRING -> NUMERIC -> INT
or
SELECT CAST(CAST (MyVarcharCol AS NUMERIC(19,4)) AS INT)
When copying data from TableA to TableB, the conversion is implicit, so you dont need the second convert (if you are happy rounding down to nearest INT):
INSERT INTO TableB (MyIntCol)
SELECT CAST(MyVarcharCol AS NUMERIC(19,4)) as [MyIntCol]
FROM TableA

Try this one, it worked for me in Athena:
cast(MyVarcharCol as integer)

Related

How do I convert a varchar into a negative number?

I have a table where a column has data such as ($23,324.09). If it's $23,324.09, then I can convert it to money, then a float. But the ( ) is causing errors when I try that. Will I have to apply a UDF to that column or is there another way to convert such a value.
NOTE: I don't have control on how the data gets to that table.
You could also use PARSE or TRY_PARSE
SELECT TRY_PARSE('($23,324.09)' AS MONEY USING 'en-US')
Returns
-23324.09
using a few replace():
declare #col varchar(32) = '($23,324.09)'
select convert(decimal(19,4),replace(replace(replace(replace(#col,'(','-'),',',''),')',''),'$',''))
returns: -23324.0900
Running a simple test, this is runs in about 1/3rd of the time as the parse() equivalent.
dbfiddle: http://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=675f6eb70986bd24880c66a8be4f5cbd
Here is a shorter alternative that uses the money data type:
select convert(money,replace(replace(#col,'(','-'),')',''))
dbfiddle: http://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=31bfc3e1e48b8f863e89bcef9a6ffddc

Why does MS SQL CAST as bigint result in int overflow?

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)

Syntax error while converting varchar to numeric in sql

I want to convert a varchar to numeric, I looked aroud and found SELECT CAST. I tried to use it like this this:
SELECT CAST(`Elo` AS INT) FROM Table `Rankings`;
However, I get a syntax error. Is there anything wrong?
Remove the Table keyword from your query.
SELECT CAST(`Elo` AS INT) FROM `Rankings`;

Convert nvarchar to bigint in Sql server 2008

I want insert all rows of a table into another table, and I also want convert a nvarchar field into bigint, but when I use convert(bigint, col1) SQL Server shows an error:
Error converting data type nvarchar
to bigint
How can I fix this problem?
You could try to use ISNUMERIC to determine those rows that are indeed numeric:
UPDATE dbo.YourTable
SET BigIntColumn = CAST(NVarcharColumn AS BIGINT)
WHERE ISNUMERIC(NVarcharColumn) = 1
That would convert those rows that can be converted - the others need to be dealt with manually.
You should convert bigint to nvarchar not vice versa
cast(Other_Column_name as nvarchar) not cast (Column_Name as bigint)
you can try this:
CAST(CAST(col1 as NUMERIC) as BIGINT)
Here I convert navrchar value of column into bigInt and than perform Addition of thos two columns find blow :
SELECT (CAST(col1 AS BIGINT) + CAST(col2 AS BIGINT)) AS TotalValue from tableName

how to insert multiple values which is the output of a select query

Select
cast(ltrim(rtrim(Substring(string,charindex('my',string)+len('my')+5,
charindex('for the company',string)-charindex('my',string)+len('my')-9))) as datetime)
from table
Select
cast(ltrim(rtrim(Substring(string,charindex('company',string)+len('company')+1,
len(String)-charindex('company',string)+len('company')-9)))as varchar)
from description
this 2 queries has a set of rows as output.
I want to insert these values to another table using single insert.
What i did is:
insert into table2(orderid,orderdate)
Select
cast(ltrim(rtrim(Substring(String, len('The order number')+1,
CHARINDEX ( 'as been created at', String) - len ('as been created at')))) as int)
,
cast(ltrim(rtrim(Substring(string,charindex('at',string)+len('at')+5,
charindex('for the company',string)-charindex('at',string)+len('at')-9))) as datetime)
from description
but its not inserted..its showing error like The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value..
Is there any another way to insert this?
when inserting a datetime you should specify a string that is SQL compliant i.e.
'YYYY-MM-DD HH:MM:SS'
I suspect that the CAST function cant convert the type specified. However you dont need to convert to a datetime, you can simply insert the string representation of the datetime.
Other issues you may encounter are the casting of ltrim(rtrim()) to an int. LTRIM, RTRIM both return a varchar. CHARINDEX already returns an int.
Ensure your types are consistent
To insert output from your two queries into a single table, the data types and number of columns from these queries should match with that of the table. You can use convert
CONVERT(
DATETIME,ltrim(rtrim(Substring(
string,charindex('at',string)+len('at')+5,
charindex('for the company',string)-charindex('at',string)+len('at')-9)))
,112)
for your datetime column and try (provided your target table has a datetime column for OrderDate).