Convert string to date format 105 in sql server - sql-server-2008

I had string in the order of ddmmyy i.e '231013' which i need to convert it into dd-mm-yy format
I tried following but it is giving yyyy-dd-mm format
I know 105 will give dd-mm-yy format
DECLARE #ITEMS AS NVARCHAR(10)='231013'
SELECT CONVERT(DATE,#ITEMS,105)
but it is returning
2023-10-13
How to convert string in the order of ddmmyy to date dd-mm-yy

Convert string in the order of ddmmyy to date dd-mm-yy
DECLARE #ITEMS AS NVARCHAR(10)='231013'
SELECT CONVERT(varchar(25),
CONVERT(DATE, SUBSTRING(#ITEMS, 1, 2) + '-' + SUBSTRING(#ITEMS, 3, 2) + '-' + SUBSTRING(#ITEMS, 5, 2), 5),5)
result will be

It seems that the mmddyy style is not natively supported by CONVERT; to perform the conversion, I would just adapt the input string to one of the supported styles, like mm-dd-yy:
SELECT
CONVERT(DATE, SUBSTRING(#ITEMS, 1, 2) + '-' + SUBSTRING(#ITEMS, 3, 2) + '-' +
SUBSTRING(#ITEMS, 5, 2), 5)

If you just need to change the format (Not converting to a DateTime type), you could Stuff() it:
Declare #Items as nvarchar(10)='231013' --ddmmyy
Select Stuff(Stuff(#Items,3,0,'-'),6,0,'-') --dd-mm-yy
Fiddle demo

Related

Convert decimal to euro currency in MYSQL

What is the best way to select a decimal value from the mysql database and convert it to an euro currrency in the mysql selection.
When i select "format(multiplier * (coalesce(Invoice.rent, 0) + coalesce(Invoice.furnished, 0) + coalesce(Invoice.gwe, 0) + coalesce(Invoice.service, 0) + coalesce(Invoice.gas, 0) + coalesce(Invoice.electricity, 0) + coalesce(Invoice.water, 0) + coalesce(Invoice.heat, 0) + coalesce(Invoice.tax, 0) + coalesce(Invoice.internet_tv, 0)) - coalesce(sum(Payment.amount),0),2)"
It returns a number like this 1,000.25 i want it to be 1.000,25 what is the best way to do this in MYSQL select query?
The documentation reveals that FORMAT() has up to three arguments (emphasis mine):
FORMAT(X,D[,locale])
Formats the number X to a format like '#,###,###.##', rounded to D
decimal places, and returns the result as a string. If D is 0, the
result has no decimal point or fractional part.
The optional third parameter enables a locale to be specified to be
used for the result number's decimal point, thousands separator, and
grouping between separators. Permissible locale values are the same as
the legal values for the lc_time_names system variable (see Section
10.7, “MySQL Server Locale Support”). If no locale is specified, the default is 'en_US'.
That could be a starting point. (You apparently want the format provided by the de_DE locale.)
Demo
In database you cant change default decimal separator from . to , for reason described here insert-non-english-decimal-points-in-mysql.
You can use this function to format your output value:
CREATE FUNCTION f_change_decimal_separator(num_value VARCHAR(16)) RETURNS VARCHAR(16)
BEGIN
DECLARE char_value VARCHAR(16);
SET char_value = REPLACE(num_value, ".", ";");
SET char_value = REPLACE(char_value, ",", ".");
SET char_value = REPLACE(char_value, ";", ",");
RETURN char_value;
END;

Migration of mysql dates in integer format

I want to migrate dates from integer format to DATETIME.
My dates in my old database have the following format:
olddb.table.date = 20131114 (INT)
olddb.table.time = 900 (INT) (9 AM, 24h clock)
new database:
newdb.table.datetime = 2013-11-14 9:00:00 (DATETIME)
How would I migrate this with purely SQL?
SELECT CAST(CONCAT(DATE(olddb.table.date),' ',TIME(olddb.table.time*100)) AS DATETIME);
You can convert your date part with STR_TO_DATE (MySQL documentation):
STR_TO_DATE(olddb.table.date, "%Y%m%d")
And for the time part, you can use the same function :
STR_TO_DATE(olddb.table.time, "%h%i")
Then, you can concatenate date and time parts and apply function to concatenation result :
STR_TO_DATE(concatenated_value, "%Y%m%d%h%i")
Where concatenated_value is built with :
CONCAT(olddb.table.date, olddb.table.time)
Try this:
cast(
concat(
table.date div 10000, '-',
lpad((table.date mod 10000) div 100, 2, '0'), '-',
lpad(table.date mod 100, 2, '0'), ' ',
table.time div 100, ':',
lpad(table.time mod 100, 2, '0'))
as datetime)
Here's a working example:
http://www.sqlfiddle.com/#!2/1ff75/1

How to check date range in mssql for epoch datetime

in one of the table the date column values are like below
date
25052008112228
26052008062717
table name is transaction
i tried using the below query but its throwing error
select * from transaction where date between '2012-01-06' and '2012-06-30'
select * from transaction where date between '2012/01/06' and '2012/06/30'
give me a solution.
The problem is that the [date] column doesn't contain a date in a format that will be automatically converted to an appropriate datetime value - it doesn't even contain a supported format value. So you're left shredding the text using string operations:
declare #Transactions table (TDate char(14))
insert into #Transactions (TDate) values
('25052008112228'),
('26052008062717')
select CONVERT(datetime,
SUBSTRING(TDate,5,4) + '-' +
SUBSTRING(TDate,3,2) + '-' +
SUBSTRING(TDate,1,2) + 'T' +
SUBSTRING(TDate,9,2) + ':' +
SUBSTRING(TDate,11,2) + ':' +
SUBSTRING(TDate,13,2))
from
#Transactions
Results:
2008-05-25 11:22:28.000
2008-05-26 06:27:17.000
You could wrap the CONVERT/SUBSTRING operations into a UDF, if you need to perform this kind of conversion often. Of course, ideal would be to change the column definition to store a genuine datetime value - almost all datetime issues arise when people treat them as text.
(Note, I've renamed both the table and the column, since using reserved words is usually a bad idea)
Your query could be something like:
;with converted as (
select *,CONVERT(datetime,
SUBSTRING([Date],5,4) + '-' +
SUBSTRING([Date],3,2) + '-' +
SUBSTRING([Date],1,2) + 'T' +
SUBSTRING([Date],9,2) + ':' +
SUBSTRING([Date],11,2) + ':' +
SUBSTRING([Date],13,2)) as GenuineDate
from [Transaction]
)
select * from converted where GenuineDate between '20120106' and '20120630'
(Note that I've also changed the date literals in the final query to a safe format also)
-- asp time stamp
select * from [transaction] where
cast(SUBSTRING([date],5,4) + '-' + SUBSTRING([date],3,2) + '-' +
SUBSTRING([date],1,2) + ' ' + SUBSTRING([date],9,2) +
':' + SUBSTRING([date],11,2) + ':' +
SUBSTRING([date],13,2) as datetime)
between '2008-05-26' and '2012-01-06'
-- unix epoch time
select * from [transaction] where [date]
between DATEDIFF( SECOND, '01-01-1970 00:00:00', '2012-01-06' )
and DATEDIFF( SECOND, '01-01-1970 00:00:00', '2012-06-30')

adding current date as a parameter to a query in clover ETL

I have a query block for retrieving data from MSSQL Server. the query has some hardcoded date values which needs to be changed everyday to import the daily feed. I need to automate this execution. I am using cloverETL for executing the query right now.
Here is the query (its a query to retrieve sharepoint activity data)
use
DocAve_AuditDB;
DECLARE
#ParameterValue VARCHAR(100),
#SQL
VARCHAR(MAX)
SET
#SQL = STUFF((SELECT 'UNION ALL SELECT COL_ItemTypeName, COL_UserName, COL_MachineIp, COL_DocLocation, DATEADD(SECOND, COL_Occurred / 1000, ''19700101 00:00'') as Date_Occurred, COL_EventAction FROM '+ TABLE_NAME + ' WHERE DATEADD(SECOND, COL_Occurred / 1000, ''19700101 00:00'') BETWEEN '+ '''20120515'''+ 'AND' + '''20120516'''+ 'AND ' + 'COL_ItemTypeName='+ '''Document''' AS 'data()'
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_NAME LIKE '%2012_05%'
FOR
XML PATH('')),1,10,'')
EXEC
(#SQL)
In the above block I want the TABLE_NAME LIKE param i.e. %2012_05% to be a variable retrieved from the current data and also the date values in the between clause
BETWEEN '+ '''20120515'''+ 'AND' + '''20120516'''
to be todays date-1 and todays date
should create a small java program for handling this or it can be done directly in the query itself? if yes how?
Thanks in Advance
Use GETDATE() or CURRENT_TIMESTAMP to obtain the current date (and time).
Use CONVERT() with the 112 format specifier to convert the current timestamp to a string formatted as YYYYMMDD.
Use DATEADD() for calculations (like subtracting one day) on dates/times.
Use SUBSTRING() to subtract parts from the formatted date string to rearrange them to the %YYYY_MM% format.
Or you can use inline ctl notation in DBInputTable:
SELECT 'UNION ALL SELECT COL_ItemTypeName, COL_UserName, COL_MachineIp, COL_DocLocation, DATEADD(SECOND, COL_Occurred / 1000, ''19700101 00:00'') as Date_Occurred, COL_EventAction FROM `date2str(today(), "yyyy_MM")` WHERE DATEADD(SECOND, COL_Occurred / 1000, ''19700101 00:00'') BETWEEN '+ '''`date2str(today(), "yyyyMMdd")`'''+ 'AND' + '''`date2str(dateAdd(today(),1,day), "yyyyMMdd")`'''+ 'AND ' + 'COL_ItemTypeName='+ '''Document''' AS 'data()'

How to format int to price format in SQL?

I select the price 1000000 and I need to format it to $1,000,000. How can I do that in SQL?
To format with commas, you can use CONVERT with a style of 1:
declare #money money = 1000000
select '$' + convert(varchar, #money, 1)
will produce $1,000,000.00
If you want to remove the last 3 characters:
select '$' + left(convert(varchar, #money, 1), charindex('.', convert(varchar, #money, 1)) - 1)
and if you want to round rather than truncate:
select '$' + left(convert(varchar, #money + $0.50, 1), charindex('.', convert(varchar, #money, 1)) - 1)
Creating Function:
CREATE FUNCTION [dbo].[f_FormatMoneyValue]
(
#MoneyValue money
)
RETURNS VARCHAR(50)
AS
BEGIN
RETURN cast(#MoneyValue as numeric(36,2))
END
Using in Select Query:
Select dbo.f_FormatMoneyValue(isnull(SalesPrice,0))SalesPrice from SalesOrder
Output:
100.00
Formatting Money Value with '$' sign:
CREATE FUNCTION [dbo].[f_FormatMoneyWithDollar]
(
#MoneyValue money
)
RETURNS VARCHAR(50)
AS
BEGIN
RETURN '$' + convert(varchar, #MoneyValue, 1)
END
Output:
$100.00
Note: The above sample is for the money field. You can modify this function according to your needs
Hope this helps you..! :D
SELECT FORMAT(price, 'C2', 'en-us')
The SQL Server money datatype is just decimal(10, 4). To my knowledge there is no datatype that will present the way you want.
Adding the dollar sign and commas is something that should belong in the application logic, but if you really must do it through a database object consider adding the dollar sign, and commas every three characters (after the decimal point). In other words, you'll have to convert the int to varchar and do string manipulation.
It depends, however, there's no simple way to do it in standard SQL specs(SQL-92, SQL-2003, etc.).
For PostgreSQL PL/pgSQL and Oracle PL/SQL, you can use to_char to format numbers:
select to_char(1234567.123, 'FM$999,999,999.99')
Which gives output:
$1,234,567.12
See: http://www.postgresql.org/docs/7/static/functions2976.htm