Remove decimal values using SQL query - sql

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}

Related

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)')

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

Reg: Auto incrementing a value in SQL Table

I got a value in a field called it (EmployeeDetailKey - varchar(10)) with sequential values such as
00001, 00002, 00003....
It is in a table Employeedetail. When ever a new Employee detail has to be inserted I have to get the max(EmployeeDetailKey) and increment by 1 and store it back. If I have 10 employeedetail records that need to be inserted then the same procedure has to follow.
If the max(EmployeeDetailKey) = 00003 then after inserting 10 records
it has to be 00013. Later on after inserting let us say 100 records it has to
be 00113.
How can I do it in the form of MS-SQL statement.
Please note the column cannot be identity type.
Just add an identity column to your table. I would suggest something like:
IntEmployeeDetailKey int not null identity(1, 1) primary key,
. . .
Then add a computed column:
EmployeeDetailKey as (right(('00000' + cast(IntEmployeeDetailKey as varchar(10)), 5)
Then SQL Server will do the incrementing automatically. And you can get the value out as a zero-padded string.
If you prefer a solution without changing the table structure, then:
Cast your zero-padded string value to int. This is easy in SQl server, as it will easily convert such strings to numbers:
SELECT CAST('00003' AS int)
This will return integer value of 3.
Find MAX()
Just perform MAX() on column you've just converted to string, like...
SELECT MAX(CAST(mycolumn AS int)) FROM mytable
Actually, you don't have to do a conversion, as SQL server will sort the values correctly in original string representation.
Increment
This is easy, since you now have the integer value, so...
SELECT MAX(CAST(mycolumn AS int)) + 1 FROM mytable
Convert it back to zero-padded string
SQL Server 2008 is a bit tricky to tame here, since left-padding is not his speciality. However, starting from in SQL Server 2012, there is a FORMAT function available, so, you can use...
SELECT FORMAT(MAX(CAST(mycolumn AS int)) + 1, '00000') FROM mytable
If you have only SQL Server 2005 or 2008 available, you can use REPLICATE() combined with LEN() to get what you need (disclaimer: UGLY CODE):
SELECT REPLICATE('0', 5 - LEN(MAX(CAST(mycolumn AS int)) + 1)) + CAST((MAX(CAST(mycolumn AS int)) + 1) AS nvarchar(5)) FROM mytable
EDIT As Luaan hinted, you can use another padding option (shorter and more readable code):
SELECT RIGHT('00000' + CAST(MAX(CAST(mycolumn AS int) + 1) as nvarchar(5)), 5) FROM mytable
I don't know if it is mandatory that EmployeeDetailKey must have this format.
I'll suggest you to substitute the datatype from varchar(10) to IDENTITY.
IDENTITY is a sort of special data type that gets automatically incremented by SQL Server each time you insert a row in the parent table. You can learn more here: https://msdn.microsoft.com/en-us/library/ms186775.aspx
If you need to present it with leading zeroes you can always select it like this (liberally adapted from here: Most efficient T-SQL way to pad a varchar on the left to a certain length?):
SELECT right('00000'+ rtrim(EmployeeDetailKey), 5) FROM YourTable

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.

Converting varchar to numeric type in SQL Server

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).