mssql convert varchar to float - sql-server

I have a field value productlength of 0.123. This is from a view and has a data type of varchar.
I need to convert it to a float or numeric value so as o perform math comparisons.
convert(float,productlength)
and
cast(productlength as float) both do not work.
error varchar cant be converted to float or somethiing liek that.
From what I have read varchar can simply not be converted to a numeric string?
Any clever ways around this?

You can convert varchars to floats, and you can do it in the manner you have expressed. Your varchar must not be a numeric value. There must be something else in it. You can use IsNumeric to test it. See this:
declare #thing varchar(100)
select #thing = '122.332'
--This returns 1 since it is numeric.
select isnumeric(#thing)
--This converts just fine.
select convert(float,#thing)
select #thing = '122.332.'
--This returns 0 since it is not numeric.
select isnumeric(#thing)
--This convert throws.
select convert(float,#thing)

Use
Try_convert(float,[Value])
See
https://raresql.com/2013/04/26/sql-server-how-to-convert-varchar-to-float/

DECLARE #INPUT VARCHAR(5) = '0.12',#INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, #INPUT) YOUR_QUERY ,
case when isnumeric(#INPUT_1)=1 THEN CONVERT(float, #INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED
above will return values
however below query wont work
DECLARE #INPUT VARCHAR(5) = '0.12',#INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, #INPUT) YOUR_QUERY ,
case when isnumeric(#INPUT_1)=1 THEN CONVERT(float, #INPUT_1) ELSE **#INPUT_1** END AS YOUR_QUERY_ANSWERED
as #INPUT_1 actually has varchar in it.
So your output column must have a varchar in it.

Related

Conversion failed when converting the varchar value '$400,000.00' to data type int

I have the following part of query that works fine:
CONVERT(varchar(15), CONVERT(money, AmountOfInsurance), 1) AS AmountOfInsurance
I want to prevent anounts that are equal to 0 to show up formated, just to show up: 0, so I added this CASE statement but I get the following error:
CASE WHEN AmountOfInsurance > 0 THEN '$' + CONVERT(varchar(15), CONVERT(money, AmountOfInsurance), 1) ELSE 0 END AS AmountOfInsurance
Any idea?
Your ELSE should be '' because you want to return a varchar. Now the CASE expression has two data types and INT takes precedence over varchar, that's why it tries to convert the varchar back to INT.
Added for reference:
Data Type Precedence
Just another option (if 2012+) is Format() with a conditional format.
Declare #YourTable table (AmountOfInsurance money)
Insert Into #YourTable values
(400000),
(2500),
(0)
Select format(AmountOfInsurance,IIF(AmountOfInsurance>0,'$#,##0.00','0'))
From #YourTable
Returns
$400,000.00
$2,500.00
0
Use the CAST function to cast
DECLARE #text AS NVARCHAR(10)
SET #text = '100$'
SELECT CASE WHEN AmountOfInsurance > 0 THEN CAST(#text AS MONEY) ELSE 0 END

SQL Server - error converting data type nvarchar to float

I am inserting table A to table B. The problematic column looks like -$25.2. I first replaced the $ and tried insert. Got this error
Error converting data type nvarchar to float.
I then checked by
SELECT *
FROM B
WHERE ISNUMERIC([Col Name]) <> 1
and no results were returned.
This is odd. It is supposed to return something.
What should I check next?
I also tried something like
CAST(REPLACE([Col Name], '-$', '') AS FLOAT)
Try using this
DECLARE #Text nvarchar(100)
SET #Text = '-$1234.567'
SET #Text = Replace(#Text,'$', '')
Select CONVERT(float, #Text) AS ColumnValue
Select ABS(CONVERT(float, #Text)) AS ColumnValue
While the 'money' data type isn't great for doing calculations, in this scenario you can use it as an intermediary.
declare #a nvarchar(10)
set #a = '-$25.2'
select
#a,
cast(cast(#a as money) as float)
Only use this though if your data only goes to a max of 4 decimal places, otherwise you will lose precision in the conversion.

Error while cast data from nvarchar to numeric

I have table1 with two columns:
col1 - nvarchar(510)
col2 - nvarchar(510)
I want to take all the values from table1 and put it to table2 where data type is different:
col1_A - numeric(22,10)
col2_A - int
I'm doing like:
insert into table2
select cast(col1 as numeric), cast(col2 as int)
but I'm getting error:
What is wrong?
You probably have a character in table1.col1. Also, it's important to point out that table1.col1 is nvarchar(510) but if len(table1.col1) > 11 you are going to get an Arithmetic overflow error.
declare #char nvarchar(510)
set #char = '123456789101'
--set #char = '1234567891011' --will cause an arithmetic overflow error since you are using numeric(22,10)
--set #char = '123abc456' --will cause Error converting data type nvarchar to numeric
declare #num numeric(22,10)
set #num = cast(#char as numeric(22,10))
select #num
It means you need to sanitize your data. Find which values are causing the issue and then manually correct them first or exclude them. To find which values are not numeric use the ISNUMERIC function.
select col1
from yourtable
where ISNUMERIC(col1) = 0
thank you Eric for help to find wrong recrods!
I did case as below:
case
when [col1] LIKE '%,%' then REPLACE([col1]),',','')
else CAST([col1] as Numeric)
end
and it's working!

Can not select rows where column values are empty string in SQL Server?

I have a column which has varchars like "172.54". I am trying to insert into another table where this columns datatype is float. I am getting error saying can not convert datatype varchar to float. So I do
SELECT *
FROM TBL
WHERE ISNUMERIC(COLNAME) <> 1
And I get no results. But casting is not working. So I look and I have empty strings in that column. So I try to
SELECT *
FROM TBL
WHERE COLNAME = ''
And also every other different amount of spaces.
I ultimately just want to convert the empty strings to null
Also len(colname) = 1
declare #test varchar(10) = ' ' -- any number of spaces is equivalent to ''
select try_convert( float, #test ) as floatval -- '' gives you 0
select case when #test = '' then NULL else try_convert( float, #test ) end as floatval -- value '' returns NULL instead of 0
I guess you column has some characters other than numeric data. Also empty string will be converted to zero it will not throw error.
To filter Numeric data use
COLNAME not like '%[^0-9]%'
Try something like this
insert into tablename (col1,col2)
SELECT col1,col2 FROM TBL
COLNAME not like '%[^0-9]%'

Converting varchar to int, SQL Server

I have code like this:
CREATE FUNCTION gantistok (#id VARCHAR(8),
#id_t INT)
RETURNS INT
BEGIN
DECLARE #tahu INT,
#tempe INT,
#hasil INT;
SELECT #tahu = CONVERT(INT, stok)
FROM barang
WHERE id_barang = #id;
SELECT #tempe = CONVERT(INT, jumlah)
FROM det_trans
WHERE id_det_trans = #id_t;
SET #hasil = #tahu - #tempe;
RETURN #hasil
END
Why doesn't it work? I am getting this error:
Msg 402, Level 16, State 1, Procedure gantistok, Line 5
The data types text and varchar are incompatible in the equal to operator.
you are using wrong syntax
it should be
CONVERT(expr,type)
and type must be SIGNED [INTEGER]
REFERENCE
MySQL? SQL Server? which one?
What is type of id_barang stok for table barang?
Guessing the problem expression is id_barang=#id
The SQL Server convert() function does not allow convert TEXT to int(INT4).
problem is on id_barang = #id.
id_barang contains a value that RDBMS is not able to convert to integer.
id_barang is a varchar.
So if you can't convert id_barang to integer, then you have to convert #id to varchar in the query:
SELECT #tahu = CONVERT(INT, stok)
FROM barang
WHERE id_barang = CONVERT(varchar(50), #id);
I'm using varchar(50) because I don't know what kind of varchar exactly id_barang is.
I would suggest to always do it this way.
Even if id_barang would not contain non-integer values at the moment...it's still a text column!
Someone could insert a non-integer value anytime, so I would always make sure that my queries will work in this case as well.

Resources