SQL: Query integer column in specific format - sql

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.

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

How to add Leading Zeroes and Decimal Points at the same time in SQL?

I have tried many combinations of the SQL functions; so as to have a 12 digit number including the dot character, including leading zeroes and decimal points.
For example:
for the number 121.22, I want to format it to 000000121.22
or for the number 12.2, I want to format it to 000000012.20
or for the number 100, I want to format it to 000000100.00
I have used the following function; but I lost the decimal points if it's zero.
SELECT RIGHT('000000000000'+ STR(CONVERT(VARCHAR,MYNUMBER),12,2),12);
Any idea on how to solve this problem in Microsoft SQL?
If you're on SQL Server 2012 or later, you can use the format() function.
SELECT FORMAT(121.22, '000000000000.00')
SELECT FORMAT(12.2, '000000000000.00')
000000000121.22
000000000012.20
for ms sql versions not in (2012,2014):
cast(right('000000000',9-len(floor(the_number))) as varchar)
+ cast( cast(the_number as decimal(10,2))as varchar)
for ms sql versions in (2012,2014):
format(the_number ,'000000000000.00')
SELECT padded_id = REPLACE(STR(id, 12), SPACE(1), '0')
Is what I add to use (In SQL server) leading 0's as needed, change the 12 to whatever total number of digits you want it to be.
This allows for non hard coded values, just make sure id or whatever column/param you want to format is set.

SQL Convert output from decimal to comma

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 |

SQL query for first digits of a numeric field

I have a NUMERIC(5, 0) field in a IBM db2 database from which I only want the first 4 digit. I haven't been able to achieve what I want with using CAST.
How can I achieve this in SQL without casting as a String and using substring ?
Ex: 13525 --> 1352
Thanks for your help!
Why not cast as a string and use substring?
You can also do:
select (case when field >= 10000 then floor(field / 10) else field end)
This assuming that if the field has 1234, then you want 1234 rather than 0123.
EDIT:
You can also use a string by using two calls to cast():
select cast(left(cast(field as varchar(5)), 4) as numeric(4, 0))
I should also note that in many databases, you can just do:
select left(field, 4)
and the database will do the appropriate conversions. I don't have DB2 nearby to check this.

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