Snowflake cast Int to Decimal - sql

I'm working on Migrating SQL Server data to Snowflake and trying to convert Int to Decimal. But the response is not what I'm expecting.
In SQL If you run this query Select 1.0000 or Select Cast(1 as Decimal(12,4)) the result will 1.000.
If I do the same in Snowflake the result is 1. Is there a way to fix it?
Thanks

You can use
select to_number(1,12,4)
For more info

Select Cast(1 as Decimal(12,4)) the result will 1.000. If I do the same in Snowflake the result is 1. Is there a way to fix it?
Representation of the number does not matter. It is most likely a client tool that shows it without decimal places.
When EXPLICIT cast is involved the data type is set as requested and it could be easily confirmed with DESCRIBE RESULT:
SELECT CAST(1 AS DECIMAL(12,4)) AS col;
DESCRIBE RESULT LAST_QUERY_ID();
-- name type kind null?
-- col NUMBER(12,4) COLUMN Y
DECIMAL and NUMBER are synonyms in Snowflake.

Related

How to cast varchar value to decimal?

I have a column that is currently set as nvarchar(max) and I want to convert the column to decimal(38,2). The problem I am running into is that a few of the millions of rows are in the format of -1.943E12 and because the E is present I get an error, Cannot convert nvarchar into numeric, when I try to cast the column into a decimal. Is there anyway to do this?
CREATE TABLE practice (cost nvarchar(max))
INSERT INTO practice values ('123'),('44232.99'),('43.4432'),('1.943E12')
SELECT CAST(cost as decimal(32,2)) FROM practice
What I'm ultimately trying to do is insert data from a staging table (where all columns are nvarchar(max)) into a table with appropriate datatypes. I kept getting an error, so after digging through each of the 40 columns, I found 5 columns where this scientific notation occurs. Any advice on how to do this at scale without having to check each column?
INSERT INTO practice_corrected_datatypes
SELECT * FROM practice
Numeric cannot convert from exponential format, but float can. Therefore you could do this by going via float. For example:
print cast(cast('1.943E12' as float) as decimal(38,2))
assuming you have try_parse() and try_cast()
SELECT try_cast(try_parse(cost as float) as decimal(32,2))
FROM practice
The advantage is that they return NULL instead of failing. You could probably get by with just the inner try_parse()
SELECT cast(try_parse(cost as float) as decimal(32,2))
FROM practice
Try this...
update p
set cost = cast(cast(cost as float) as decimal(32,2))
from practice p
where cost like '%E%'

Get the greatest value in a nvarchar column

I'm developing a database with SQL Server 2012 SP2.
I have a table with a NVARCHAR(20) column, and it will have numbers: "000001", "000002", etc.
I need to get the greatest value in that column and convert it to int. How can I do it?
I have found that I can convert a nvarchar to int with this sql sentence:
SELECT CAST(YourVarcharCol AS INT) FROM Table
But I don't know how can I get the max value in that column because the numbers are nvarchar.
UPDATE:
By the way, this column is NVARCHAR because I need to store text on it. I'm testing my solution and I need to store ONLY numbers to test it.
If your numbers are padded like in the example given and all have the same width, you can just sort them alphanumerically and then cast the max-value to INT or BIGINT (depending on your numbers range).
If there are very many rows it was much faster, especially if there is an index on this column...
Something like
SELECT TOP 1 * FROM YourTable
ORDER BY NumberColumn DESC
or, if you need the max-value only:
SELECT MAX(NumberColumn) FROM YourTable
If you have to deal with negative numbers or differently padded numbers you have to cast them first
SELECT TOP 1 * FROM YourTable
ORDER BY CAST(NumberColumn AS INT) DESC
or
SELECT MAX(CAST(NumberColumn AS INT)) FROM YourTable
Please note:
If you've got very many rows, the second might get rather slow. Read about sargable
If your NumberColumn might include invalid values, you have to check, Read about ISNUMERIC().
The best solution - in any case - was to use an indexed numeric column to store these values
Try this one...
I think MAX is enough.
SELECT max(CAST(YourVarcharCol AS INT)) FROM Table
Try this
SELECT MAX(t.Y) from (SELECT CAST(YourVarcharCol AS INT) as Y FROM Table) t
You should try this on finding the highest value:
SELECT MAX(CAST(YourVarcharCol AS INT)) AS FROM Table
If all the data follow the same padding and formatting pattern, a simple max(col) would do.
However, if not, you have to cast the values to int first. Searching on a columns cast to some other datatype will not use an index, if there's any, but will scan the whole table instead. It may or may not be OK for you, depending on requirements and number of rows in the table. If performance is what you need, then create a calculated column as try_cast( col as int), and create an index on it.
Note that you should not use cast, but try_cast instead, to guard against values that can't be cast (if you use a datatype to store something which is essencially of another datatype, it always opens up a possibility for errors).
Of couse, if you can change the original column's type to int, it would be the best.
This will return max int value
SELECT MAX(IIF(ISNUMERIC(YourVarcharCol) = 1, YourVarcharCol, '0') * 1) FROM Table
You can use like this
select max(cast(ColumnName AS INT ))from TableName

Determine if a Varchar field has a Numeric entry

I've got a field in a table that has a DataType of varchar(10). This field contains numeric values that are formatted as a varchar, for the sole purpose of being used to join two tables together. Some sample data would be:
AcctNum AcctNumChar
2223333 2223333
3324444 3324444
For some records, the table sometimes thinks this field (AcctNumChar) is numeric and the join doesn't work properly. I then have to use an Update statement to re-enter the value as a varchar.
Is there any way to determine whether or not the field has a varchar or numeric value in it, using a query? I'm trying to narrow down which records are faulty without having to wait for one of the users to tell me that their query isn't returning any hits.
You can use isnumeric() for a generic comparison, for instance:
select (case when isnumeric(acctnum) = 1 then cast(acctnum as decimal(10, 0))
end)
In your case, though, you only seem to want integers:
(case when acctnum not like '%[^0-9]%' then cast(acctnum as decimal(10, 0))
end)
However, I would strongly suggest that you update the table to change the data type to a number, which appears to be the correct type for the value. You can also add a computed column as:
alter table t add AcctNum_Number as
(case when acctnum not like '%[^0-9]%' then cast(acctnum as decimal(10, 0))
end)
Then you can use the computed column rather than the character column.
There are several ways to check if varchar column contains numeric value but I recommend to you to us TRY_CONVERT function.
It will give you NULL if the value cannot be converted to number. For example, to get all records that have numeric values, you can do this:
SELECT *
FROM [table]
WHERE TRY_CONVERT(INT, [value]) IS NOT NULL
You can use CAST and CONVERT (Transact-SQL) functions here to solve your purpose.
reference here - https://msdn.microsoft.com/en-IN/library/ms187928.aspx.
IsNumeric worked, TRY_CONVERT didn't (SQL wouldn't recognize it as a built-in function for some reason). Anyway, for the record I ran the following query and got all of my suspect records:
SELECT *
FROM ACCT_LIST
where IsNumeric([ACCT_NUM_CHAR]) = 0
Use PATINDEX function:
DECLARE #s VARCHAR(20) = '123123'
SELECT PATINDEX('%[^0-9]%', #s)
If #s variable will have something different from range 0-9 this function will return the index of first occurence of non digit symbol. If all symbols are digits it will return 0.

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}

SQL Convert statement

I need help with a SQL convert statement. I have NetQuanity (masterTable) which is a varchar(15) and I have another table with Purchase price (PO TABLE) which is money. When I try to multiply them in a SQL view is gives me the error:
If your field is a VARCHAR, you'll need to CAST to the appropriate data type prior to your operation. e.g.
CAST(myVarCharField as INT) * myIntField
Be forewarned however, if you attempt to CAST this field to a numeric data type and it's not numeric, you'll be in the same boat.
I would recommend using CAST over CONVERT in your example, for the following reason defined in this SO post:
Related: T-SQL Cast versus Convert
Maybe try using the CONVERT function? CONVERT(money,NetQuantity).
First of all you have a data definition problem.
The first thing is to eliminate any non-numeric entries in the master table.
SELECT whatever FROM masterTable WHERE ISNUMERIC(NetQuanity)=1
The next step is to include this as a sub-query in the calculation.
In this query use CONVERT or CAST to convert the valid quanities to integer.
i.e.
CONVERT(INT, NetQuantity)