How to Convert CYYMM to YYYY-MM - sql

I have some date columns that are formatted as CYYMM (e.g. 12012). I would like to convert these to a typical data representation in SQL Server.
FYI. C stands for century.
E.g. 12012 should be 2020-12 (for December of 2020)
Another
11210 should be 2012-10 (for October of 2012).
How could I go about accomplishing this efficiently and 1900-safe. For example I have accomplished doing it like :
declare #dte int = 12012;
select '20' + left(substring(cast(#dte as char(5)), 2, 5),2) + '-' + right(#dte,2)
But I would like to know if there is a more native solution that doesn't rely on hard coding the '20'.

Assuming first character would be 1 or 0
declare #dte int = 02012;
Select left((#dte/10000+19),2)+stuff(right(#dte,4),3,0,'-')
Results
1920-12

Related

SQL Server: convert and merge separate date and time columns (both integers)

I am working on a query, where I have to fill a table's column ([Result_DateTime]) with datetime values.
The datetime based on two columns, both integer. One contains the date and the other is the time, as it is.
As you can see from the picture, it is a bit difficult to merge and convert these values to an actual datetime, because of the way they are stored. Mainly the time value causing problems.
I concluded how to convert the date column:
CONVERT(DATETIME, LEFT(20200131, 8))
but then I got stuck - what to do with the time and how to merge the two into one datetime effectively?
Using function STUFF looks nasty...
Could you help me out please? I am using SQL Server 2014
Below is one method to do it:
SELECT CAST(Convert(DATE, LEFT(DATEUPDT, 8)) AS VARCHAR(10)) +' '+CAST (TIMEUPDT/100 AS VARCHAR(4)) + ':' + CAST(TIMEUPDT%(100 * (TIMEUPDT/100)) AS VARCHAR(10))+':00'
FROM TEST_TABLE_TIME;
I think I found one solution. What I tried is to avoid using varchar conversions because of how the time column's zeros are cut off. However, I am not convinced that this is the most effective way to do so:
DECLARE #DateInt int = 20200131
DECLARE #TimeInt int = 345 -- 03:45:00
SELECT CONVERT(DATETIME, LEFT(#DateInt, 8)) +
CAST(DATEADD(second, FLOOR(#TimeInt / 100) * 3600 + FLOOR(#TimeInt / 1) % 100 * 60, 0) as datetime)
I was testing it with various time values, it is working.

Hardcode a specific day in data time while pulling the data - SQL

Actually I have different date in SQL table when I pull those via SQL query, day of datetime field should have fixed day.
Example: (DD-MM-YYYY) day should be "7" > (7-MM-YYYY)
10-08-2007 > 07-08-2007
27-12-2013 > 07-12-2013
01-03-2017 > 07-03-2017
Can someone help me on this. Thanks in Advance.
Find the difference between 7 and the day of the original date and add that to the original date:
SELECT DATEADD(DAY, 7 - DAY(OriginalDate), OriginalDate)
Use DATEPART to take out the month and year parts. Cast those into varchar and concatenate with 07.
Query
select '07-' +
cast(DATEPART(mm, [date_column]) as varchar(2)) + '-' +
cast(DATEPART(yyyy, [date_column]) as varchar(4))
from your_table_name;
Assuming You might have to change the day number example
DECLARE #dayNum char(2)
SELECT #dayNum = '07'
select #dayNum + Right(convert(char(10),getdate(),105),8)
If that is not the case You could do this
select '07'+ Right(convert(char(10),'10-08-2007',105),8)
I'd go this way:
SELECT CONVERT(DATE,CONVERT(VARCHAR(6),GETDATE(),112)+'25',112);
CONVERT with format 112 will return the date as unseparated ISO (today we would get 20170407). Convert this to VARCHAR(6) will implicitly cut away the day's part (201704).
Now we add a day and use again CONVERT with 112, but now with DATE as target type.
One thing to keep in mind: The day you add must be two-digit. You can achieve this with
DECLARE #int INT=7;
SELECT REPLACE(STR(#int,2),' ','0');
Use DATEFROMPARTS: Updated ONLY works from 2012 - OP has tagged SQL-Server 2008
select DATEFROMPARTS ( year('10-08-2007'), month('10-08-2007'), 7 )
Assuming that your field is of datetime datatype and your fixed day is of integer type.
select datetimecolumn+(yourparamfixedday-datepart(dd,datetimecolumn))

How to perform arithmetic function in DATE TIME in SQL

I have four columns namely-
1. C_Date in YYYYMMDD format (varchar(255)) Eg. 20161231
2. C_Time in 4-digit Military format (varchar(255)) Eg. 2143
3. E_Date in YYYYMMDD format (varchar(255)) Eg. 20161230
4. E_Time in 4-digit Military format (varchar(255)) Eg. 1600
I want to Calculate the time between E event and C event. How can i perform this computation with a select statement?
Pretty simple to create a date type from the component values:
with data as (select '20161231' as c_date, '2143' as c_time)
select
convert(
datetime,
stuff(stuff(stuff(c_date + ' ' + c_time, 12, 0, ':'), 7, 0, '-'), 5, 0, '-'),
120
) as c_datetime
from data;
Use datediff() to calculate the time difference. You didn't specify how you wanted the output to look so I won't attempt a guess. There should be a hundred other questions out there with information relevant to your question though.
Also note that I did not append ':00' to the string to represent seconds. It seems to work though I couldn't track down an official document to confirm that. So to be safe you may want to tack that on as well. Arguably there could be a more universal format like ISO 8601 that would be a "better" solution. You get the idea though.
A small matter to convert your strings into a datetime. Then we use DateDiff() to calculate the differance between the two dates.
Declare #YourTable table (C_Date varchar(255),C_Time varchar(255),E_Date varchar(255),E_Time varchar(255))
Insert Into #YourTable values
('20161231','2143','20161230','1600')
;with cte as (
Select *
,CDT = try_convert(DateTime,C_Date+' '+stuff(C_Time,3,0,':'))
,EDT = try_convert(DateTime,E_Date+' '+stuff(E_Time,3,0,':'))
from #YourTable
)
Select CDT
,EDT
,Duration = concat(DateDiff(DD,EDT,CDT),' ',Format(DateAdd(Second,DateDiff(SECOND,EDT,CDT),'1899-12-31'),'HH:mm:ss'))
,AsSeconds = DateDiff(SECOND,EDT,CDT)
,AsMinutes = DateDiff(MINUTE,EDT,CDT)
From cte
Returns
CDT EDT Duration AsSeconds AsMinutes
2016-12-31 21:43:00 2016-12-30 16:00:00 1 05:43:00 106980 1783

How to convert date format from 05-JUN-99 to 050599?

I have gone through the suggested date formats here but didn't find any that meets my requirement.
I have the following date format:
05-JUN-99. 05 being dd as in day, JUN and the year 1999.
I have been asked to convert that to mmddyy (two digit month, two digit day and two digit year).
Any ideas how to do this?
Thanks for your assistance
You can use convert here.
select convert(varchar(20),cast('05-JUN-99' as date),10)
--Output: 06-05-99
select replace(convert(varchar(20),cast('05-JUN-99' as date),10),'-','')
--Output: 060599
Date Styles from the documentation
My Vote use FORMAT for SQL-SERVER 2012 +
SELECT FORMAT(CAST('05-JUN-99' AS DATETIME),'MMddyy')
This means no nested replaces, no extraneous cast/converts etc. keeps it tidier IMHO
I usually just convert to string. Get the year, month, day, put them each in a string and concatinate them.
Declare #InputValue Varchar(16) = '05-JUN-99'
set #InputValue = replace(#InputValue,'-','/')
declare #TestDate DateTime
set #TestDate = convert(DateTime,#InputValue)
select #TestDate
select right ('0' + convert(Varchar(2),DATEPART(mm,#TestDate)),2)
+ right ('0' + convert(Varchar(2),DATEPART(dd,#TestDate)),2)
+ right ('0' + convert(Varchar(4),DATEPART(yy,#TestDate)),2)

Concatenate two date parts

I'm trying to build a report based on a ticketing system we use. I'm quite new to SQL and just getting my head around it but the issue I am facing at the moment is trying to join two fields into a date. The data in the table is in displayed as Month_Number and Year_Number
I need to do a comparison with a datetime field to see if it is between the date range. I've searched a fair bit about concatenating the two fields I have into a date but unfortunately have come up short.
You can simply do this to concatination for youe Month & Date Part.
declare #month varchar(10);
declare #year varchar(10)
set #month = 5
set #year = 2014
You can choose whatever you feel for you is the best
select #month+'-1-' +#year as Your_Date
select '1-'+#month+'-' +#year as Your_Date
select #year+'-'+#month+'-1' as Your_Date
Output
5-1-2014
1-5-2014
2014-5-1
To Retrieve the date from your Table in SQL you can do like this
select month_number+'-1-' +year_number as Your_Date
from table_name
If you want to change the style of the displaying output then you can use Convert Function