Converting varchar to numeric type in SQL Server - sql

I have a column in a table with a varchar datatype. It has 15 digits after the decimal point. Now I am having a hard time converting it to a numeric format.. float, double etc.
Does anyone have any suggestions?
Example :
Table1
Column1
-------------------
-28.851540616246499
-22.857142857142858
-26.923076923076923
76.19047619047619
I tried using the following statements and it doesn't seem to work :
update table1
set Column1 = Convert(float,column1)..
Any suggestions ?

You can use the decimal data type and specify the precision to state how many digits are after the decimal point. So you could use decimal(28,20) for example, which would hold 28 digits with 20 of them after the decimal point.
Here's a SQL Fiddle, showing your data in decimal format.
Fiddle sample:
create table Table1(MyValues varchar(100))
insert into Table1(MyValues)
values
('-28.851540616246499'),
('-22.857142857142858'),
('-26.923076923076923'),
('76.19047619047619')
So the values are held as varchar in this table, but you can cast it to decimal as long as they are all valid values, like so:
select cast(MyValues as decimal(28,20)) as DecimalValues
from table1
Your Sample
Looking at your sample update statement, you wouldn't be able to convert the values from varchar to a numeric type and insert them back in to the same column, as the column is of type varchar. You would be better off adding a new column with a numeric data type and updating that.
So if you had 2 columns:
create table Table1(MyValues varchar(100), DecimalValues decimal(28,20))
You could do the below to update the numeric column with the nvarchar values that have been cast to decimal:
update Table1
set DecimalValues = cast(MyValues as decimal(28,20))

I think you're trying to actually change the data type of that column?
If that is the case you want to ALTER the table and change the column type over to float, like so:
alter table table1
alter column column1 float
See fiddle: http://sqlfiddle.com/#!6/637e6/1/0
You would use CONVERT if you're changing the text values to numbers for temporary use within a query (not to actually permanently change the data).

Related

Redshift, casting of a decimal value is not rounding off

I have a reshift table, which has a decimal column of (38, 29), but the original data's maximum Integer part is 6 and scale is 12 i.e Decimal (18,12). But the table is created using the max precision and scale. So all the data in that has 0's at the end of the scale part as padding.
For Example:
12345.123456789112300000000000000000000
All the data in the table is like the above example.
Now I'm retrieving the data from the table using the below query.
select cast(column as decimal(30,6)) from table;
The output I'm getting is
12345.123456
But when I try the below query
select cast(12345.123456789112300000000000000000000 as decimal(30,6)) from table;
The output I'm getting is
12345.123457
I want to know why this is happening. when I cast the column in the table, it is not rounding off to its highest value, it is just truncating.
But when I try with the decimal itself it is truncating and it is rounding off.
I also want to how to achieve the second query's result in the table itself.
So this comes down to when is a cast not a cast. If I cast and integer to an int it does nothing. Casting a varchar to a shorter varchar is nearly as simple as long as the data fits. Casting a decimal to a lower scale decimal is also a simplistic operation as it is not changing the data type, just some attribute of it (scale). What you desire is that Redshift implicitly ROUNDS the values when you make this conversion and it is not. (I'll let the database philosophers debate if this is a bug or not.)
Here's a simple example to highlight this:
drop table if exists goo;
create table goo (rownum int, num decimal(30,6));
insert into goo select 1, 12345.123456789112300000000000000000000::text;
insert into goo select 2, 12345.123456789112300000000000000000000::decimal(38,29);
insert into goo select 3, 12345.123456789112300000000000000000000::double;
select rownum, num::text from goo;
In all 3 of these examples there is an implicit cast to the data type of the column 'num' in the table. However you can see that what is getting into the table is different. Lots of experiments can be set up like this. (Note that I'm casting the result to text to avoid any bench precision changes.)
The answer in your case is to explicitly ROUND() the value.

Why is SQL converting Varchar value to Integer in a varchar column?

I am receiving an error
Conversion failed when converting the varchar value to data type int
while trying to insert data from one table into another. Both have the same table structure (table being inserted is an exact copy of the one used in the Select) and data types on the columns are the same.
INSERT INTO PS_PSOPRDEFN_BA
SELECT *
FROM PSOPRDEFN
Error:
Conversion failed when converting the varchar value '11000_600' to data type int.
The column this is inserting with this value is a varchar(30) in both tables, so I don't know why SQL is trying to convert it to int. Any ideas are appreciated.
When doing inserts, always include the columns:
INSERT INTO PS_PSOPRDEFN_BA ( . . . ) -- column list here
SELECT . . . -- column list here
FROM PSOPRDEFN;
You have a value which is a string which is being assigned to an integer column, and the value cannot be converted.
When doing an insert, the columns are aligned by order in the column list, not by name. So, merely having the same name doesn't mean that the code will work. The tables have to have exactly the same columns defined in the same order with compatible types for your code to work.

db2 casting double to varchar without losing zeros

I have to check for wrong values using regexp_like expression. As far as I am concern I can do this only on strings and my data is saved in database as double.
I tried to cast it
SELECT column
FROM table
WHERE NOT REGEXP_LIKE(CAST(DECFLOAT(column) as VARCHAR(25)), '(\d{6}\.?\d{2})|(\d{7}\.?\d)')
Unfortunately values like 1234567.0 are converted into 1234567 and as a result this query is returning it as a mistake.
The other solution like
SELECT column
FROM table
WHERE NOT REGEXP_LIKE(CAST(CAST(column AS DECIMAL(8,1)) AS VARCHAR(25)), '(\d{6}\.?\d{2})|(\d{7}\.?\d)')
leads to a problem where values like 134567.89 are converted to 1234567.8 and are not returned by the query as an incorrect value.
Is there a way to cast it to varchar without giving it a range?
For 1st Query, Don't Convert column to DECFLOAT.
SELECT column
FROM table
WHERE NOT REGEXP_LIKE(CAST(CAST(column as DECIMAL(8,2)) as VARCHAR(25)), '(\d{6}\.?\d{2})|(\d{7}\.?\d)')
For 2nd Query, Increase the fraction part of the DECIMAL(8,1) to DECIMAL(8,2) to get the desired Result.
SELECT column
FROM tabel
WHERE NOT REGEXP_LIKE(CAST(CAST(column AS DECIMAL(8,2)) AS VARCHAR(25)), '(\d{6}\.?\d{2})|(\d{7}\.?\d)')

Remove decimal values using SQL query

I am having following values in database table :
12.00
15.00
18.00
20.00
I want to remove all decimal ZEROS from all values , So how can I do this using SQL query. I tried replace query but that is not working.
I want values like :
12
15
18
20
My replace query :
select height(replace (12.00, '')) from table;
Please help.
Since all your values end with ".00", there will be no rounding issues, this will work
SELECT CAST(columnname AS INT) AS columnname from tablename
to update
UPDATE tablename
SET columnname = CAST(columnname AS INT)
WHERE .....
Here column name must be decimal.
select CAST(columnname AS decimal(38,0)) from table
Simply update with a convert/cast to INT:
UPDATE YOUR_TABLE
SET YOUR_COLUMN = CAST(YOUR_COLUMN AS INT)
WHERE -- some condition is met if required
Or convert:
UPDATE YOUR_TABLE
SET YOUR_COLUMN = CONVERT(INT, YOUR_COLUMN)
WHERE -- some condition is met if required
To test you can do this:
SELECT YOUR_COLUMN AS CurrentValue,
CAST(YOUR_COLUMN AS INT) AS NewValue
FROM YOUR_TABLE
As I understand your question, You have one table with column as datatype decimal(18,9).
And the column contains the data as follows:-
12.00
15.00
18.00
20.00
Now if you want to show record on UI without decimal value means like (12,15,18,20) then there are two options:-
Either cast this column as int in Select Clause
or may be you want to update this column value like (12,15,18,20).
To apply, First very simple just use the cast in select clause
select CAST(count AS INT) from tablename;
But if you want to update your column data with int value then you have to update you column datatype
and to do that
ALTER TABLE tablename ALTER COLUMN columnname decimal(9,0)
Then execute this
UPDATE tablename
SET count = CAST(columnname AS INT)
First of all, you tried to replace the entire 12.00 with '', which isn't going to give your desired results.
Second you are trying to do replace directly on a decimal. Replace must be performed on a string, so you have to CAST.
There are many ways to get your desired results, but this replace would have worked (assuming your column name is "height":
REPLACE(CAST(height as varchar(31)),'.00','')
EDIT:
This script works:
DECLARE #Height decimal(6,2);
SET #Height = 12.00;
SELECT #Height, REPLACE(CAST(#Height AS varchar(31)),'.00','');
If it's a decimal data type and you know it will never contain decimal places you can consider setting the scale property to 0. For example to decimal(18, 0). This will save you from replacing the ".00" characters and the query will be faster. In such case, don't forget to to check if the "prevent saving option" is disabled (SSMS menu "Tools>Options>Designers>Table and database designer>prevent saving changes that require table re-creation").
Othewise, you of course remove it using SQL query:
select replace(cast([height] as varchar), '.00', '') from table
Your data type is DECIMAL with decimal places, say DECIMAL(10,2). The values in your database are 12, 15, 18, and 20.
12 is the same as 12.0 and 12.00 and 12.000 . It is up to the tool you are using to select the data with, how to display the numbers. Yours either defaults to two digits for decimals or it takes the places from your data definition.
If you only want integers in your column, then change its data type to INT. It makes no sense to use DECIMAL then.
If you want integers and decimals in that column then stay with the DECIMAL type. If you don't like the way you are shown the values, then format them in your application. It's up to that client program to decide for instance if to display point or comma for the decimal separator. (The database can be used from different locations.)
Also don't rely on any database or session settings like a decimal separator being a point and not a comma and then use REPLACE on it. That can work for one person and not for the other.
You can use the floor function.
Example:
Select FLOOR(${selectedColumn}) from ${tableName}

Change SQL Field Data Type varchar to float with data already stored

I have an imported database which contain lots of float field.
When I imported it, all the float field converted to string and I need to convert it back.
I try alter table to change the data type but I keep getting error (even if the row is empty or null).
EDIT : The server is curently down so I can't get the error message at the moment. My DBMS is SQL Server.
you can do so if all data are really numeric type.
There may be some data which hv null --no problem here.
There may be some data which are blank(('') but not null--problem is because of this.
First you make a select query to retrieve all data which are blank
say,
Select * from table1 where col=''
now update these rows with null
update table1 set col=null where col=''
After this,I think you can easily convert it to float
References: error converting data type varchar column to float.
You can first add a new field in your table with datatype float and then update it using convert function:
UPDATE #tbl
SET
num = convert(FLOAT, text)
SELECT *
FROM
#tbl