SQL Convert output from decimal to comma - sql

I have sql query (Eg. select amount from purchase_order) which outputs something like 123.45. Instead I want it output it like 123,45 (German numeral system). How do I do that?

Use the REPLACE function
SELECT REPLACE(amount, '.',',') FROM purchase_order
Keep in mind that this will replace all values that match, so in this case all periods would be replaced with commas

Use the replace function (Convert to char beforehand,if necessary). Example:
REPLACE ( TO_CHAR(amount), '.', ',')`.
Even better: set your locale properly. Thereafter all number lexicalisations should follow the respective convention.
There may also be the option to decide on a case-by-case basis. Example (Oracle syntax; you specify 2 characters, the decimal point and the group separator. For German, this would be ,., for English .,, resp.):
TO_CHAR ( amount, '9999D99', 'NLS_NUMERIC_CHARACTERS='',.''' )

use stuff string function to replae the(.) by (,)
select stuff(amount ,charindex('.', amount),1,',')
from purchase_order

"needs to be done on the db side because there are calculations involved after this"
Then don't worry about the format. In the database it's just a number. Any calculations will apply to the number itself regardless of how it's observed. Formatting only gets applied when you view the number. Don't do any formatting prior to calculations.
Do formatting at the very last layer - the UI/reporting layer.

With SQL Server 2012, you have the FORMAT function.
There is no need to do this on the db side even if calculations are involved after this...
So try this :
SQL Fiddle
MS SQL Server 2012 Schema Setup:
CREATE TABLE purchase_order
([amount] money)
;
INSERT INTO purchase_order
([amount])
VALUES
(123.45)
;
Query 1:
select FORMAT ( amount, 'G', 'de-de' ) AS 'amount'
from purchase_order
Results:
| AMOUNT |
|----------|
| 123,4500 |

Related

How can I use data from a string in SQL in a numeric comparison?

I'm a B-grade SQL user, so bear with me. I have a field that is in the NVARCHAR format ("Year"), but all but only about 1 in 1000 records is something other than a number. Yes, this is a ridiculous way to do this, but we receive this database from a customer, and we can't change it.
I want to pull records from the database where the year field is greater than something (say, 2006 or later). I can ignore any record whose year doesn't evaluate to an actual year. We are using SQL server 2014.
I have created an embedded query to convert the data to a "float" field, but for whatever reason, I can't add a where clause with this new floating-point field. I originally tried using a "case-if" but I got the same result.
I'm pulling my hair out, as I'm either missing something really silly, or there's a bug in SQL server. When I look at the field in the little hint, it's showing as a float. When I run this, I get "Error converting data type nvarchar to float."
SELECT VL.Field_A,
VL.FLYear,
VL.Field_B
FROM
(select
Field_A,
cast ([Year] as float) as FLYear,
/* didn't work either*/
/*Convert(float, [Year]) as FLYear, */
Field_B
from CustomerProvidedDatabaseTable
where (Field_A like 'E-%' OR
Field_A like 'F-%')
and
(isnumeric(year)=1)
and
year is not null
) VL
/* this statement is the one it chokes on */
where
VL.FLYear >= 2006.0
If I remove the last "where" clause, it works fine, and the field looks like a number. If I change the last where clause to:
where VL.FLYear like '%2006%'
SQL Server accepts it, though of course it doesn't return me all the records I want.
Try to simplify it and just use TRY_CONVERT(DATETIME, aYearvalue) or TRY_PARSE which will return NULL for values it can't convert and continue to process valid rows. I think you can do away with the where clause as join and just work directly against the column like: (substitute the literal string after datetime with your column)
SET DATEFORMAT mdy;
Select YEAR(try_convert(datetime, '08/01/2017')) as value1
WHERE value1 >=2016;
Try cast/convert to a numeric data type. I have modified the last line of your query to do just that. Take a peek.
SELECT
VL.Field_A,
VL.FLYear,
VL.Field_B
FROM
(select
Field_A,
cast ([Year] as float) as FLYear,
/* didn't work either*/
/*Convert(float, [Year]) as FLYear, */
Field_B
from CustomerProvidedDatabaseTable
where (Field_A like 'E-%' OR
Field_A like 'F-%')
and
(isnumeric(year)=1)
and
year is not null
) VL
/* this statement is the one it chokes on */
where
ISNUMERIC(VL.FLYear) = 1
and
CAST(VL.FLYear AS INT) >= 2006
Check out the following link for cast and convert documentation:
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
NOTE: ISNUMERIC will return true ( a false positive for a value which has a scientific numerical value, e.g. 1E10, though I don't see this happening from your data).
Another option is TRY_CONVERT.
Documentation on TRY_CONVERT: https://learn.microsoft.com/en-us/sql/t-sql/functions/try-convert-transact-sql
Try using Cast . Use the below link to check in more detail about casting.
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

SQL convert nvarchar to float

I have a table with a column Quantity; in the original table this column is defined as nvarchar(100) so I need to cast it as float to be able to do some analysis:
CAST([Quantity] AS FLOAT) AS Quantity
The issue is that I have some values which can not be converted to float like No-Quantity, Return etc. I to have filter to exclude these values and then convert rest to float.On option is use where clause:
WHERE Quantity IN ('Return', 'Sales')
This is not the best way since if we have anew values in the original table then I need to figure out what it is and add it to the where clause.
I am wondering is there is better way to identify non-convertible values?
If your SQL Server supports TRY_CONVERT, this could provide a nice solution:
SELECT TRY_CONVERT (float, [Quantity]) ...
will give you the converted values or NULL depending on the input. This could be helpful if you don't have strict control over the data.
In any database, you can use cast() and something like this:
(case when quantity not in ('No-Quantity', 'Return', . . .)
then CAST([Quantity] as float)
end) as Quantity
The in list would be the list of known string values.
You can also do a fast-and-dirty check like this:
(case when left(quantity, 1) between '0' and '1'
then CAST([Quantity] as float)
end) as Quantity
(Note: you may need to use substr() or substring() instead of left().)
And, in general, any specific database has specific functions that can help with the conversion, such as try_convert() mentioned in a comment.
Another way (if you can't use TRY_CONVERT)
SELECT CAST(quantity AS float)
FROM myTable
WHERE IsNumeric(quantity) = 1 AND quantity IS NOT NULL

How to convert number to dollar format

I wrote sql to convert number to dollar format by referring other stackoverflow questions.
select decimal(sum_price, 9, 2) from order_tbl
The data type of column sum_price is Decimal(10,0).
if number in column is 7050, this SQL return 7084.00, but what I want is
70.84.
what should I do?
You can't convert in implicit way this.
If you have stored your field in decimal(10,0) you tell you have only int part stored, so you must apply a math conversion as follow:
SELECT sum_price * 0,01 from order_tbl
But... If you have stored a number as follow: 7050 where you indicate 7,050 (US separator for thousand), how query understand this situation?
I strongly advice to change your field definition
try this
Select Str(float_field, 25, 5)
This is the link for your refrence.
https://msdn.microsoft.com/en-us/library/ms189527.aspx

SQL: Query integer column in specific format

I am trying to query a column of type (int) into a string of format (000). For example: If the column value was 1 then the output of the query should be 001
Depends on which database engine you use.
In SQL Server 2012 and higher:
SELECT FORMAT(7, 'D3')
The result is this string:
007
For older versions of SQL Server, see the accepted answer by shree.pat18
For MySQL, look here: Adding a leading zero to some values in column
For PostgreSQL, look here: Padding zeros to the left in postgreSQL
Try this:
select right('000' + convert(varchar(3), intcolumn), 3) from yourtable
Note that the output is of type varchar. If you will need this output as a number somewhere else, I would suggest doing the formatting in your UI code and keeping it as a number in the query.

Display money with decimal in sql server 2008

I am having some number in DB table column, i have written stored procedure to format that number. The requirement is i need to display the number with comma and decimal points. I have tried below, but only comma is coming.. any solutions,
PARSENAME(CONVERT(VARCHAR,CAST(TotalAmount/1000 as MONEY),1),2)
Actual result: 1,134
Expected result: 1,134.0
I want to do this in SQL server itself.
You can accomplish currency formatting as:
SELECT CONVERT(varchar, CAST(5555 AS money), 1)
but i would suggest doing such formatting on the front end, not on the data side