Formatting the SQL query result based on a pattern - sql-server

I have got a table that contains deferent type of date formats:
########
DateTime
########
10/05/2015
11/05/2015
1/5/2015
01/5/2014
Now my question is that How can I select all the rows based on this pattern \d{2}/\d{2}/\d{4} the format the result with this pattern \d{4}/\d{2}/\{2}?
The first one is dd/mm/yyyy and I would like the result be yyyy/mm/dd

Test Data
DECLARE #TABLE TABLE (Dates VARCHAR(20))
INSERT INTO #TABLE VALUES
('10/05/2015'),
('11/05/2015'),
('1/5/2015'),
('01/5/2014')
Query
The following query will convert all the values to proper sql server date data type.
SELECT CONVERT(DATE,
RIGHT('0000' + PARSENAME(REPLACE(Dates , '/','.'),1),4)
+ RIGHT('00' + PARSENAME(REPLACE(Dates , '/','.'),2),2)
+ RIGHT('00' + PARSENAME(REPLACE(Dates , '/','.'),3),2)
)
FROM #TABLE
Result
2015-05-10
2015-05-11
2015-05-01
2014-05-01
Once you have got the values in well-formatted sql server date type, you can extend the query to get the required output yyyy/mm/dd by doing the following:
SELECT CONVERT(VARCHAR(10),
CONVERT(DATE,
RIGHT('0000' + PARSENAME(REPLACE(Dates , '/','.'),1),4)
+ RIGHT('00' + PARSENAME(REPLACE(Dates , '/','.'),2),2)
+ RIGHT('00' + PARSENAME(REPLACE(Dates , '/','.'),3),2)
), 111)
FROM #TABLE
Result
2015/05/10
2015/05/11
2015/05/01
2014/05/01

In your case I you don't need to use regular expressions. A simple LIKE should suffice.
... WHERE DateTime LIKE "__/__/____" ...

Related

Convert Oracle Datetime format query to MS SQL Server Format

I have a Oracle query
SELECT to_timestamp('29-03-17 03:58:34.312000000 PM','DD-MM-RR HH12:MI:SS.FF AM')
FROM DUAL
I want to convert to SQL Server where I need to retain the Oracle date string i.e '29-03-17 03:58:34.312000000 PM':
SELECT
CONVERT(DATETIME, REPLACE(REPLACE('29-03-2017 03:58:34.312000000 PM','-', '/'),'000000 ', ''), 131)
I tried the above query, as 131 format closely matches '29-03-17 03:58:34.312000000 PM' format 'dd/mm/yyyy hh:mi:ss:mmmAM' but only difference is with the year.
In Oracle year is 17 and SQL Server the year is 2017. I need to prefix 20 to the year to make it 2017. This query converts into Hijri datetime. I need it in Gregorian datetime format.
This is the documentation.
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
I need to convert the date which is in string in Oracle format to SQL Server equivalent. Is there any way where the format like 'dd/mm/yyyy hh:mi:ss:mmmAM' can be mentioned instead of mentioning the date format code like 131, 101, 102 in the convert function.
You might try it like this:
DECLARE #oracleDT VARCHAR(100)='29-03-17 03:58:34.312000000 PM';
SELECT CAST('<x>' + #oracleDT + '</x>' AS XML).value(N'(/x/text())[1]','datetime');
It seems, that XML is implicitly able to do this correctly...
EDIT: The above is culture related!
It worked on my (german) system, but if you set the correct dateformat you can force this (be aware of side effects for the current job!)
Try this and then remove the -- to try alternative date formats. Or try with GERMAN:
SET LANGUAGE ENGLISH;
SET DATEFORMAT mdy;
--SET DATEFORMAT ymd;
--SET DATEFORMAT dmy;
DECLARE #oracleDT VARCHAR(100)='01-02-03 03:58:34.312000000 PM';
SELECT CAST('<x>' + #oracleDT + '</x>' AS XML).value(N'(/x/text())[1]','datetime');
Another approach
You might split the string in all parts and build a convertible format like this:
DECLARE #oracleDT VARCHAR(100)='29-03-17 03:58:34.312000000 PM';
WITH AllParts(Casted) AS
(
SELECT CAST('<x>' + REPLACE(REPLACE(REPLACE(REPLACE(#oracleDT,'.','-'),' ','-'),':','-'),'-','</x><x>') + '</x>' AS XML)
)
SELECT CONVERT
(DATETIME,
DATENAME(MONTH,'2000'+Casted.value(N'x[2]/text()[1]','nvarchar(max)')+'01') + ' '
+ Casted.value(N'x[1]/text()[1]','nvarchar(max)') + ' '
+ N'20' + Casted.value(N'x[3]/text()[1]','nvarchar(max)') + ' '
+ Casted.value(N'x[4]/text()[1]','nvarchar(max)') + ':'
+ Casted.value(N'x[5]/text()[1]','nvarchar(max)') + ':'
+ Casted.value(N'x[6]/text()[1]','nvarchar(max)') + ':'
+ LEFT(Casted.value(N'x[7]/text()[1]','nvarchar(max)'),3)
+ Casted.value(N'x[8]/text()[1]','nvarchar(max)'),109)
FROM AllParts
Although I don't really understand the need to use a string format that does not suit conversion, but you could divide the string into parts then build it up by adding the parts to each other. The foundation part if the first 8 characters converted to datetime2 using format style 5.
select
t
, convert(varchar, converted ,121) converted
from (
select '29-03-17 03:58:34.312000000 PM' as t
) t
cross apply (
select
convert(datetime2,substring(t,1,8),5) dt2
, case when right(t,2) = 'PM' then convert(smallint,substring(t,10,2)) + 12
else convert(smallint,substring(t,10,2))
end hh
, convert(smallint,substring(t,13,2)) mi
, convert(smallint,substring(t,16,2)) ss
, convert(int,substring(t,19,9)) ns
) ca
cross apply (
select
dateadd(hh,hh,dateadd(mi,mi,dateadd(ss,ss,dateadd(ns,ns,dt2))))
as converted
) ca2
;
Note I am able to use the column aliases of the first cross apply (dt1, hh, mi, ss, ns) in the second cross apply to form the converted datetime2 value.
+--------------------------------+-----------------------------+
| t | converted |
+--------------------------------+-----------------------------+
| 29-03-17 03:58:34.312000000 PM | 2017-03-29 15:58:34.3120000 |
+--------------------------------+-----------------------------+
see: http://rextester.com/DZJ42703

SQL Query datetime issue

I have a query on SQL Server that's finding wrong results based on a datetime condition.
SET LANGUAGE Português
select distinct
CONVERT(varchar(10), DATENAME(MONTH, i9_parcelaBase.i9_data_vencimento)) + '/' + CONVERT(varchar(10),
DATENAME(YEAR,i9_parcelaBase.i9_data_vencimento)) AS Periodo,
i9_parcelaBase.i9_data_vencimento,
i9_parcelaBase.i9_data_limite_envio_nf,
i9_parcelaBase.i9_status_atual,
i9_processo_statusBase.i9_status,
i9_processo_statusBase.i9_name
--i9_nota_fiscalBase.i9_nota_fiscalid as ID
from i9_parcelaBase
left join i9_processo_statusBase
on i9_parcelaBase.i9_status_atual = i9_processo_statusBase.i9_processo_statusId
where i9_processo_statusBase.i9_entidade = 100000002
and i9_parcelaBase.i9_data_vencimento between CONVERT(varchar(10), year(getdate())-1) + '-' + CONVERT(varchar(10), month(getdate())+1) + '-1'
and CONVERT(varchar(10), year(getdate())) + '-' + CONVERT(varchar(10), month(getdate())) + '-1'
order by i9_data_vencimento asc
Basically, Month that's receiving data without '0' before (when necessary).
Sample:
Actual return: '2017-6-1'
Expected return '2017-06-01'
Can anyone help me to solve this problem?
By the look of your query, i9_data_vencimento is expected to end with just -1, not -01. You can cast the string into a date, then recast it back as a string as a way to format it:
select distinct
CONVERT(varchar(10), DATENAME(MONTH, i9_parcelaBase.i9_data_vencimento)) + '/' + CONVERT(varchar(10),
DATENAME(YEAR,i9_parcelaBase.i9_data_vencimento)) AS Periodo,
CONVERT( VARCHAR(10), CONVERT( DATETIME, i9_parcelaBase.i9_data_vencimento ), 120 ) AS i9_data_vencimento,
:
:
Also, considering that i9_data_vencimento is just a string, and assuming it always ends with '1' in the format 'yyyy-mm-1', you could use a LEFT function to strip off the last character and replace it with '01':
SELECT DISTINCT
:
LEFT(i9_parcelaBase.i9_data_vencimento, 8) + '01' AS i9_data_vencimento,
:

SQL Server: Transfer YYYYMMDD-HHMMSS to mm/dd/yyyy hh:mm:ss

My SQL Server system is 2016.
As topic, I want to convert YYYYMMDD-HHMMSS to mm/dd/yyyy hh:mm:ss, and use dynamic SQL to fulfill this.
My data looks like this:
ID
20161119-075950
20161117-110952
20161118-153406
The datatype is nvarchar.
While I used the syntax below:
SELECT convert(date,convert(varchar(max),id,130), 130) from abc
An error Conversion failed when converting date and/or time from character string. shows up. I am thinking whether it is because SQL Server cannot identify this YYYYMMDD-HHMMSS as date type, and I need to convert this to YYYYMMDD hh:mm:ss first and then mm/dd/yyyy hh:mm:ss? Feel free to shed some lights. Thanks!
Select CONVERT(VARCHAR(25) , CAST(LEFT(ID , 8) AS DATETIME), 101)
+ ' ' + LEFT(RIGHT(ID , 6) ,2) + ':'
+ SUBSTRING(RIGHT(ID , 6) , 3,2) + ':'
+ RIGHT(ID , 2)
FROM TableName
Try it like this
DECLARE #tbl TABLE(ID NVARCHAR(100));
INSERT INTO #tbl VALUES
('20161119-075950')
,('20161117-110952')
,('20161118-153406');
--This is the actual select you need:
SELECT CAST(LEFT(ID,8) AS DATETIME) + STUFF(STUFF(RIGHT(ID,6),5,0,':'),3,0,':')
FROM #tbl
Your first part is strictly 8 chars long and implicitly casteable (unseperated datetime yyyymmdd). The time part is strictly 6 chars long. I use STUFF to insert the colons. This time can be added to a DATETIME. It will be - again implicitly - casted to DATETIME.
EDIT
To reach the given format you stated in the title just convert the first part first with code 101:
SELECT CONVERT(VARCHAR(10),CAST(LEFT(ID,8) AS DATETIME),101) + ' ' + STUFF(STUFF(RIGHT(ID,6),5,0,':'),3,0,':')
FROM #tbl
This should get the format you want... but there are probably better ways.
select
convert(varchar(16),convert(date,left(ID,8)),101) +
' ' +
substring(substring(ID,10,6),1,2) +
':' +
substring(substring(ID,10,6),3,2) +
':' + substring(substring(ID,10,6),5,2)

sql-server: Convert Char(14) to Datetime?

With SQL-server 2008 database I have a char(14) data type that I want to convert to a datetime.
Example char(14) values:
20120209102026
20010131120000
The date format is yyyymmdd of some sort.
It seems like the values I posted are not the only format, because I get an "index out of range" error for some of the values. For this I can skip the ones that are not valid dates.
declare #c char(14)
select #c='20120209102026'
Select Cast(Substring(#c,1,8) + ' ' + Substring(#c,9,2)+':'+
Substring(#c,11,2)+':'+ Substring(#c,13,2) as DateTime)
Second Version that ignores out of range numeric values:
Select Cast(
Rtrim(Substring(#c,1,8)
+ Case When len(Substring(#c,9,4))>=4 then +' '+ Substring(#c,9,2) else '' end
+ Case When len(Substring(#c,11,2))=2 then +':'+ Substring(#c,11,2) else '' end
+ Case When len(Substring(#c,13,2))=2 then +':'+ Substring(#c,13,2) else '' end)
as Datetime)
This is ugly but if your format is yyyymmddhhmmss then you can use:
select cast(left(yourDate, 8)+' '+
SUBSTRING(yourDate, 9, 2)+':'+SUBSTRING(yourDate, 11, 2)+':'+RIGHT(yourDate, 2) as datetime)
from yourtable
See SQL Fiddle with Demo
A series of function calls but ends up with the same outcome.
Try like this:
select convert(datetime,STUFF(STUFF(STUFF(STUFF(STUFF('20010131120000',5,0,'/'),8,0,'/'),11,0,' '),14,0,':'),17,0,':'))
Look here for how STUFF works!

Date format in dd/MM/yyyy hh:mm:ss

I need to convert datetime from 2012-07-29 10:53:33.010 to
29/07/2012 10:53:33.
I tried using
select CONVERT(varchar(20), GETDATE(), 131)
but its showing date according to Hijri calendar
11/09/1433 10:53:33:
Please help?
SELECT FORMAT(your_column_name,'dd/MM/yyyy hh:mm:ss') FROM your_table_name
Example-
SELECT FORMAT(GETDATE(),'dd/MM/yyyy hh:mm:ss')
This can be done as follows :
select CONVERT(VARCHAR(10), GETDATE(), 103) + ' ' + convert(VARCHAR(8), GETDATE(), 14)
Hope it helps
You could combine 2 formats:
3 dd/mm/yy (British/French)
8 hh:mm:ss
according to CONVERT() function, and using + operator:
SELECT CONVERT(varchar(10),GETDATE(),3) + ' ' + CONVERT(varchar(10),GETDATE(),8)
SELECT CONVERT(CHAR(10),GETDATE(),103) + ' ' + RIGHT(CONVERT(CHAR(26),GETDATE(),109),14)
The chapter on CAST and CONVERT on MSDN Books Online, you've missed the right answer by one line.... you can use style no. 121 (ODBC canonical (with milliseconds)) to get the result you're looking for:
SELECT CONVERT(VARCHAR(30), GETDATE(), 121)
This gives me the output of:
2012-04-14 21:44:03.793
Update: based on your updated question - of course this won't work - you're converting a string (this: '4/14/2012 2:44:01 PM' is just a string - it's NOT a datetime!) to a string......
You need to first convert the string you have to a DATETIME and THEN convert it back to a string!
Try this:
SELECT CONVERT(VARCHAR(30), CAST('4/14/2012 2:44:01 PM' AS DATETIME), 121)
Now you should get:
2012-04-14 14:44:01.000
All zeroes for the milliseconds, obviously, since your original values didn't include any ....
CREATE FUNCTION DBO.ConvertDateToVarchar
(
#DATE DATETIME
)
RETURNS VARCHAR(24)
BEGIN
RETURN (SELECT CONVERT(VARCHAR(19),#DATE, 121))
END
select DATE_FORMAT(NOW(),'%d/%m/%Y %h:%m:%s')
from dual
Try this wherever required, I have used this in JpaRepository in SpringBoot Project.
This will be varchar but should format as you need.
RIGHT('0' + LTRIM(DAY(d)), 2) + '/'
+ RIGHT('0' + LTRIM(MONTH(d)), 2) + '/'
+ LTRIM(YEAR(d)) + ' '
+ RIGHT('0' + LTRIM(DATEPART(HOUR, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(MINUTE, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(SECOND, d)), 2)
Where d is your datetime field or variable.

Resources