I am trying to convert phone number from the column 'phone' from the table 'Clients'. I have tried the following syntaxes, but I still get error messages -
1. SELECT CAST(phone as int)
FROM Clients
Error: Conversion failed when converting the nvarchar value '030-3456789' to data type int
2. SELECT CONVERT(int, phone)
FROM Clients
Conversion failed when converting the nvarchar value '030-3456789' to data type int.
3. SELECT CAST(phone AS BIGINT)
FROM Clients
WHERE ISNUMERIC(phone) = 1
The query doesn't return error but there is no result, the column is empty.
It looks (from your example syntax) like you might be using SQL Server.
If that's the case and it's 2017+ you can do the following which copes with any combination of non-numeric values.
Based on your comments the following should work
select Try_Convert(bigint, Replace(Translate('(5) 789-0123','()-',' '),' ',''))
Result: 57890123
If you are using SQL Server 2016 or earlier you have to nest multiple replacements:
select Try_Convert(bigint, Replace(Replace(Replace(Replace('(5) 789-0123)','-',''),'(',''),')',''),' ',''))
Because at least some of your records cannot be covert to numeric by default, as the indicated one 030-3456789
You basically need to replace/eliminate the dash in between:
SELECT cast(replace('12-3', '-', '') as int)
Anyway, welcome to StackOverflow.
Related
When trying to convert column data type NAVCHAR to INT receiving error. Simple code below:
SELECT [phone], FORMAT(CAST(PHONE AS int),'(000)-000-0000)')
FROM Sales.Customers
Your query should be something like this:
SELECT [phone], FORMAT(CAST(REPLACE([phone],'-','')AS INT), '(000)-000-0000)')
FROM Sales.Customers
So if there's an invalid character to be converted to in (for this scenario dash is the one to be replaced), it will replace it with blank then format it with the format you want.
ex: '030-3456789'
this will become (030)-345-6789
Seems like you have rows with phone numbers stored as strings, which can't be converted to an int. To find out which, execute:
SELECT *
FROM Sales.Customers
WHERE ISNUMERIC(phone) = 0;
HTH
I would suggest using TRY_CAST():
SELECT [phone],
FORMAT(TRY_CAST(PHONE AS int), '(000)-000-0000)')
FROM Sales.Customers;
This returns NULL if the value cannot be converted -- which is better than getting an error.
I have a table which contains both text and numbers in a varchar column called EMPLOYEE_CODE. I want to ignore all the text and get the Highest number in the Column and then + 1 which i can then assign to a new employee. The code below would work on an INT Column but not on the VARCHAR because of the text i get the below error:
Conversion failed when converting the varchar value 'testusercode' to
data type int.
SELECT MAX(EMPLOYEE_CODE) + 1 as Target
FROM [COMPANY].[dbo].[USER]
WHERE EMPLOYEE_CODE + 1 NOT IN (SELECT EMPLOYEE_CODE From dbo.USER)
I am guessing I have to add convert or cast to the query but not sure how
You can use ISNUMERIC to check for number, get maximum value and add 1.
SELECT MAX(EMPLOYEE_CODE) + 1 as Target
FROM [COMPANY].[dbo].[USER]
WHERE ISNUMERIC(EMPLOYEE_CODE) = 1
If you are using newer versions of SQL Server, you can also use
SELECT MAX(EMPLOYEE_CODE) + 1 as Target
FROM [COMPANY].[dbo].[USER] WHERE TRY_PARSE(EMPLOYEE_CODE AS int) IS NOT NULL
There are TRY_CAST and TRY_CONVERT also for same stuff. You can easily check which one suits your purpose.
https://learn.microsoft.com/en-us/sql/t-sql/functions/try-cast-transact-sql
I am trying to insert data from one table to another table, but we are facing issue it gives us error of
Numeric value out of range: 8115 [Microsoft][ODBC Driver 11 for SQL
Server][SQL Server ]Arithmetic overflow error converting varchar to
data type numeric. (SQLExecDirect[8115] at /builddir
/build/BUILD/php-5.6.30/ext/pdo_odbc/odbc_driver.c:247)
We are using below query to insert data
`INSERT INTO template_150 ([ClientName],[LOB],[PharmacyTotalClaimAmt])
SELECT PharmacyID,ProductIDNDC
, REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(decimal(10,2),CONVERT(varchar(10),CONVERT(varchar(10),LEFT
(SUBSTRING(REPLACE(TRIM(IngredCost),'\',''), PATINDEX('%[0-9.-]%',REPLACE(TRIM(IngredCost),'\','')),
8000),PATINDEX('%[^0-9.-]%', SUBSTRING(REPLACE(TRIM(IngredCost),'\',''), PATINDEX('%[0-9.-]%',REPLACE
(TRIM(IngredCost),'\','')), 8000) + 'X') -1)) )
),'"',''),'$',''),',',''),'-','') AS [TRIM(IngredCost)]
FROM file_5979bd211a3a9`
I found some solution to use lenth WHERE LEN(IngredCost
)<=13 function in where condition, but if we will use this function then we will not able to insert all the records for the table file_5979bd211a3a9, we want to save all the records of table file_5979bd211a3a9, can anyone please give us solutio, how can we resolve this error ?
You're converting a 10 character number to a DECIMAL(10,2). That means up to 8 digits in the whole portion and 2 in the fractional. If there are more than 8 numbers in the whole portion of the number, you can't convert that to a DECIMAL(10,2).
For example:
select convert(decimal(10,2),'1000000000')
Try DECIMAL(12,2) or use a VARCHAR(8).
I have varying 'message' columns which is a varchar that should be an xml, but some of them may not be well-formed or valid. I am trying to weed out the rows that have a given input value to a node like this:
Select * from messagelog where message like '%1234567%'
But when I filter those to try and lift another node (1234567) whos value I do not know, I come across the issue.
I've casting every entry to a xml wont work since like 1% of messages are not valid.
This code doesn't parse the varchar into xml, but returns a substring if it exists. However, I get a conversion error on the charindex = 0 case. Some MessageIds are these large varchars.
Is there anything that I'm missing here? Am I SOL for using SQL to parse not well-formed XML varchars?
select
case when CAST(charindex('<RelatesToMessageID>', message) as varchar(100)) = 0
then 1
else
substring(message, charindex('<RelatesToMessageID>', message)+20, charindex('</RelatesToMessageID>', message)-charindex('<RelatesToMessageID>', message)-20)
end
from messagelog
Conversion failed when converting the varchar value '959B91D824324108948261EC2A81CD92' to data type int.
Your CASE is returning both a VARCHAR and an INT. You should change your then 1 to then '1' so both parts of your CASE return a VARCHAR
I saw that I could select the substring only in locations where there are an existing NCPDPID. This would get rid of the case altogether.
if exists(Select * from messagelog where message like '%<NCPDPID>1234567</NCPDPID>%')
select substring(message, charindex('<MessageID>', message)+11, charindex('</MessageID>', message)-charindex('<MessageID>', message)-11) from messagelog where message like '%<NCPDPID>1234567</NCPDPID>%'
I'm looking for a way to transform a genuine string into it's hexadecimal value in SQL. I'm looking something that is Informix-friendly but I would obviously prefer something database-neutral
Here is the select I am using now:
SELECT SomeStringColumn from SomeTable
Here is the select I would like to use:
SELECT hex( SomeStringColumn ) from SomeTable
Unfortunately nothing is that simple... Informix gives me that message:
Character to numeric conversion error
Any idea?
Can you use Cast and the fn_varbintohexstr?
SELECT master.dbo.fn_varbintohexstr(CAST(SomeStringColumn AS varbinary))
FROM SomeTable
I'm not sure if you have that function in your database system, it is in MS-SQL.
I just tried it in my SQL server MMC on one of my tables:
SELECT master.dbo.fn_varbintohexstr(CAST(Addr1 AS VARBINARY)) AS Expr1
FROM Customer
This worked as expected. possibly what I know as master.dbo.fn_varbintohexstr on MS-SQL, might be similar to informix hex() function, so possibly try:
SELECT hex(CAST(Addr1 AS VARBINARY)) AS Expr1
FROM Customer
The following works in Sql 2005.
select convert(varbinary, SomeStringColumn) from SomeTable
Try this:
select convert(varbinary, '0xa3c0', 1)
The hex number needs to have an even number of digits. To get around that, try:
select convert(varbinary, '0x' + RIGHT('00000000' + REPLACE('0xa3c','0x',''), 8), 1)
If it is possible for you to do this in the database client in code it might be easier.
Otherwise the error probably means that the built in hex function can't work with your values as you expect. I would double check the input value is trimmed and in the format first, it might be that simple. Then I would consult the database documentation that describes the hex function and see what its expected input would be and compare that to some of your values and find out what the difference is and how to change your values to match that of the expected input.
A simple google search for "informix hex function" brought up the first result page with the sentence: "Must be a literal integer or some other expression that returns an integer". If your data type is a string, first convert the string to an integer. It looks like at first glance you do something with the cast function (I am not sure about this).
select hex(cast SomeStringColumn as int)) from SomeTable
what about:
declare #hexstring varchar(max);
set #hexstring = 'E0F0C0';
select cast('' as xml).value('xs:hexBinary( substring(sql:variable("#hexstring"), sql:column("t.pos")) )', 'varbinary(max)')
from (select case substring(#hexstring, 1, 2) when '0x' then 3 else 0 end) as t(pos)
I saw this here:
http://blogs.msdn.com/b/sqltips/archive/2008/07/02/converting-from-hex-string-to-varbinary-and-vice-versa.aspx
Sorrry, that work only on >MS SQL 2005
OLD Post but in my case I also had to remove the 0x part of the hex so I used the below code. (I'm using MS SQL)
convert(varchar, convert(Varbinary(MAX), YOURSTRING),2)
SUBSTRING(CONVERT(varbinary,Addr1 ) ,1,1) as Expr1