Sql Datetime convert - sql

In a database table, I have two column storing date and time in this format:
D30DAT D30TIM
140224 75700
I need update a new field where store date in the format
2014-02-24 07:57:00.000
How I can use a SQL query to do it?

For Postgres and Oracle (assuming those columns are varchar):
select to_timestamp(dt, 'yymmdd hh24miss')
from (
select d30dat||' '||case when length(d30tim) = 5 then '0'||d30tim else d30tim end as dt
from x
) t;
The case expression adds a leading 0 if the time part only consists of 5 digits so that the format mask can be specified with always 2 digits for the hour. The blank between the two columns is essentially only a debugging aid and could be left out.
The result is a real timestamp value that can easily be formatted using to_char() to the desired format.
SQLFiddle for Postgres: http://sqlfiddle.com/#!15/ac07a/2
SQLFiddle for Oracle: http://sqlfiddle.com/#!4/ac07a2/4

Try this function. Its not particularly fast or great, but converts the fields you specified.
CREATE FUNCTION GetDateTimeFromINT
(
#Date INT,
#Time INT
)
RETURNS DATETIME
AS
BEGIN
DECLARE #YearNo VARCHAR(4)
DECLARE #MonthNo VARCHAR(3)
DECLARE #DayNo VARCHAR(2)
DECLARE #HourNo VARCHAR(2)
DECLARE #MinNo VARCHAR(2)
DECLARE #SecNo VARCHAR(2)
SET #YearNo = LEFT(CONVERT(VARCHAR,#Date), LEN(#Date)-4)
SET #MonthNo = SUBSTRING(CONVERT(VARCHAR,#Date),LEN(#Date)-3,2)
SET #DayNo = SUBSTRING(CONVERT(VARCHAR,#Date),LEN(#Date)-1,2)
SET #HourNo = LEFT(CONVERT(VARCHAR,#Time), LEN(#Time)-4)
SET #MinNo = SUBSTRING(CONVERT(VARCHAR,#Time),LEN(#Time)-3,2)
SET #SecNo = SUBSTRING(CONVERT(VARCHAR,#Time),LEN(#Time)-1,2)
SET #YearNo = '20' + #YearNo
IF LEN(#HourNo) = 1
BEGIN
SET #HourNo = '0' + #HourNo
END
SET #MonthNo = CASE
WHEN #MonthNo = '01' THEN 'JAN'
WHEN #MonthNo = '02' THEN 'FEB'
WHEN #MonthNo = '03' THEN 'MAR'
WHEN #MonthNo = '04' THEN 'APR'
WHEN #MonthNo = '05' THEN 'MAY'
WHEN #MonthNo = '06' THEN 'JUN'
WHEN #MonthNo = '07' THEN 'JUL'
WHEN #MonthNo = '08' THEN 'AUG'
WHEN #MonthNo = '09' THEN 'SEP'
WHEN #MonthNo = '10' THEN 'OCT'
WHEN #MonthNo = '11' THEN 'NOV'
WHEN #MonthNo = '12' THEN 'DEC'
END
RETURN CONVERT(DATETIME, #DayNo + '-' + #MonthNo + '-' + #YearNo +' ' + #HourNo + ':' + #MinNo + ':' + #SecNo)
END
GO
Call it like so:
SELECT *, dbo.GetDateTimeFromINT(D30DAT,T30DAT) OutputDT
FROM SourceTable
If you need help with the update statement, let me know

Because someone gave a convoluted answer in SQL Server, I want to point out that there is a much simpler way.
I also want to point out that the format is not unreasonable. It provides easy access to the date parts and it is sortable. Of course, a real date/time value has these properties as well; I am guessing that this is some legacy format from some ancient system.
In any case, try this:
with t as (select 140224 as ymd, 75700 as hms)
select cast(cast(ymd as varchar(255)) + ' ' +
stuff(stuff(right('000000' + cast(hms as varchar(255)), 6
), 3, 0, ':'
), 6, 0, ':')
from t;
This turns the numbers into the format YYMMDD HH:MM:SS which SQL Server recognizes as a date/time value. Actually it would be better to pre-pend "20" for the four-digit year, but I'm not sure what the OP wants in terms of Y2K convertibility.
Although the code would look a bit different, similar logic would work in most databases.

Related

Convert YYYYMM to MMMYY

I have a period 201604 (nvarchar). Is there a way that I can convert 201604 to APR16?
Use the DATENAME & SUBSTRING functions, like this:
declare #str nvarchar(50) = '201604'
select UPPER(left(datename(mm,cast(#str+'01' as date)),3))+substring(#str,3,2) --APR16
It is a bit ugly, but you can't use any of the built-in date formatting stuff as is. Feel free to swap out the case statement for a join if you have a month names table, etc.:
DECLARE #exampleVal NVARCHAR(6) = '201604';
SELECT CASE SUBSTRING(#exampleVal, 5, 2)
WHEN '01' THEN 'JAN'
WHEN '02' THEN 'FEB'
WHEN '03' THEN 'MAR'
WHEN '04' THEN 'APR'
WHEN '05' THEN 'MAY'
WHEN '06' THEN 'JUN'
WHEN '07' THEN 'JUL'
WHEN '08' THEN 'AUG'
WHEN '09' THEN 'SEP'
WHEN '10' THEN 'OCT'
WHEN '11' THEN 'NOV'
WHEN '12' THEN 'DEC'
END +
SUBSTRING(#exampleVal, 3, 2)
Try this:
Add '01' (as first day of month), so convert your varchar to datetime and get the datename of the month:
declare #myperiod nvarchar(10)
SET #myperiod = '201604'
SET #myperiod = #myperiod + '01'
SELECT UPPER(SUBSTRING(DATENAME(month, CONVERT(datetime, #myperiod)), 1, 3)) +
SUBSTRING(CONVERT(varchar, DATEPART(year, CONVERT(datetime, #myperiod))), 3, 4)
Add 01 at the last, so that it changes to a valid date format. Then use the datename function:
DECLARE #STRING VARCHAR(10)='201604'
SELECT DATENAME(MONTH,#STRING+'01') +' '+SUBSTRING(#STRING,3,2)
Output:
April 16
In two lines:
declare #napis varchar(6)='201506'
SELECT UPPER(LEFT(DATENAME(month, #napis+'01'),3)) + SubString(#napis,3,2)
Another option is by using Format() and DateFromParts(). This will work in SQL Server 2012 or newer versions:
Declare #Period NVarchar (6) = N'201604'
Declare #Format NVarchar (5) = N'MMMyy'
Select Upper(Format(DateFromParts(Left(#Period, 4), Right(#Period, 2), 1), #Format))
APR16
Use simple this
declare #test nvarchar(max) = '201604'
select left(DATENAME(month, #test +'01'),3) + SubString(#napis,3,2)
Another way:
DECLARE #Date varchar(6) = '201604'
SELECT REPLACE(SUBSTRING(CONVERT(char(9), CAST(#Date +'01' as Date), 6), 4, 7), ' ', '')
Try this one..
DECLARE #DATE NVARCHAR(6) = '201604'
SELECT datename(MONTH,CONVERT(DATE,CONVERT(DATE,LEFT(#DATE,4)+'.'+RIGHT(#DATE,2)+'.01',102),102))

SQL convert quarter date number to string padding 0s as prefix for numbers < 10

I want to convert monthly_dates to quarter, but I'd like to path single digit numbers with 0s.
I.e.,
monthly_date = '2015-01-01'
In the SQL query I do:
QUARTER(monthly_date)*3-2 AS varchar
but that gives me '1' instead of '01'
Is there a way to make it give me '01', '04', '07' and '10'?
Can you have quarter number bigger than 4?
Anyhow... you can pad numbers the way you want (be sure to check SQL Reference Manual > SQL Functions > Formatting Functions).
For example:
SQL> select to_char( 4 , '09' ) ;
to_char
---------
04
SQL> select to_char( 12 , '09' ) ;
to_char
---------
12
I admit, this is a brute force method but I have used it in the past.
Given these 4 variables, I can calculate the StartCalendarId with padded 0's
Declare #StartDate date
Declare #StartYear int
Declare #StartMonth int
Declare #StartDay int
Set #StartYear = Year(#StartDate)
Set #StartMonth = Month(#StartDate)
Set #StartDay = Day(#StartDate)
Set #StartCalendarId =
(CONVERT([int],
(((CONVERT([varchar](4),#StartYear)+
case when len(#StartMonth)=(1) then '0' else '' end)+
CONVERT([varchar](2),#StartMonth))+
case when len(#StartDay)=(1) then '0' else '' end)
+CONVERT([varchar](2),#StartDay))
)

TSQL - char changing to INT

I need the variable #end_period be character e.g. 01 and not 1
What is wrong with the following code?
DECLARE #start_year AS CHAR(4)
DECLARE #end_year AS CHAR(4)
DECLARE #start_period AS CHAR(2)
DECLARE #end_period AS CHAR(2)
DECLARE #start_date as datetime
DECLARE #end_date as datetime
SET #start_year = '2014'
SET #end_year = '2014'
SET #start_period = '07'
SET #end_period = '08'
SET #end_year = CASE WHEN #end_period ='12' THEN #end_year + 1 ELSE #end_year END
SET #end_period = CASE WHEN #end_period ='12' THEN '01' ELSE #end_period + 1 END
select #end_year
select #end_period
There's something weird about using CHAR. I don't know why but when I do this, I get your desired results:
DECLARE #start_year AS CHAR(4)
DECLARE #end_year AS CHAR(4)
DECLARE #start_period AS CHAR(2)
DECLARE #end_period AS CHAR(2)
DECLARE #start_date as datetime
DECLARE #end_date as datetime
SET #start_year = '2014'
SET #end_year = '2014'
SET #start_period = '07'
SET #end_period = '08'
SET #end_year = CASE WHEN #end_period ='12' THEN #end_year + 1 ELSE #end_year END
SET #end_period = CASE WHEN #end_period ='12' THEN '01' ELSE RIGHT('0'+CAST((#end_period + 1) AS varchar(2)) ,2) END
select #end_year
select #end_period
However when I change this: CAST((#end_period + 1) AS varchar(2))
To this: CAST((#end_period + 1) AS char(2))
I just get a '9' instead of '09'. Weird. I don't know why.
EDIT: MYSTERY SOLVED.
I don't know why I didn't think of this right away. Actually, I do. It's only 9 am.
The '9' that you are seeing as a result is actually '9 ' (9 with a blank space after it) because char(2) has to have 2 characters in it. So doing RIGHT('0'+'9 ') is of course going to return '9 '. You could use RTRIM() or REPLACE() to get rid of the space while preceding it with a zero if you want, or you can just use the varchar cast I illustrated above.
When you do :
#end_period + 1
Example :
'08'+1
The string '08' is converted to the integer 8, one is added, result => 9.
An implicit conversion is then made back to char(2), which is '9'.
The full matrix of possible conversions (implicit or explicit) can be found on MSDN.
To solve your problem, you can then add leading zeroes this way :
SET #end_period = CASE WHEN #end_period ='12' THEN '01' ELSE RIGHT('00' + CAST((#end_period + 1) as VARCHAR(2)), 2) END
Try
SET #end_period = CASE WHEN #end_period = '12' THEN '01'
ELSE CASE WHEN #end_period > 8 THEN CONVERT(VARCHAR,#end_period + 1)
ELSE '0' + CONVERT(VARCHAR,#end_period + 1)
END
END

Date in MON-YYYY format to Text format

How do I convert date format field to MON-YYYY format.
I have date 12-06-2014 and I want to compare it with JUN-2014.
Here is a link that explains everything about date format:
Date Format
Your solution is probably the following (MySQL version):
UPPER(DATE_FORMAT(yourDate, '%b-%Y'))
And for SQL Server:
UPPER(SUBSTRING(DATENAME(MONTH, yourDate), 1, 3) + '-' + CAST(DATEPART(YEAR, yourDate) AS VARCHAR(4)))
Hope this will help you
The SQL Server syntax is:
UPPER(FORMAT(yourDate, 'MMM-yyyy'))
SQL supports a number of different date formats, but does not support non-numeric based date formats. I would strongly suggest finding a method which uses one of these formats as suggested the Microsoft SQL documentation.
Alternatively, if it is absolutely necessary that you use this format, then the following code can change any date format into the format you have requested.
declare #date date = '2014-01-01'
select
case when DATEPART(mm,#date) = 1 then 'JAN'
when DATEPART(mm,#date) = 2 then 'FEB'
when DATEPART(mm,#date) = 3 then 'MAR'
when DATEPART(mm,#date) = 4 then 'APR'
when DATEPART(mm,#date) = 5 then 'MAY'
when DATEPART(mm,#date) = 6 then 'JUN'
when DATEPART(mm,#date) = 7 then 'JUL'
when DATEPART(mm,#date) = 8 then 'AUG'
when DATEPART(mm,#date) = 9 then 'SEP'
when DATEPART(mm,#date) = 10 then 'OCT'
when DATEPART(mm,#date) = 11 then 'NOV'
when DATEPART(mm,#date) = 12 then 'DEC' end
+ '-'
+ CONVERT(char(4),DATEPART(yy,#date)) as new_format
You could use something like the following to format the date and compare (SQL Fiddle):
SELECT *
FROM
(
SELECT
CONCAT(
CONVERT(CHAR(3), CONVERT(DATE, MyDateField, 105), 0),
'-',
DATEPART(YYYY, CONVERT(DATE, MyDateField, 105))
) AS DF
FROM MyTable
) m
WHERE m.DF = 'JUN-2014';
You can use below for convert date formate.
select left(datename(mm,[Date]),3)
+'-' + cast( DATEPART(YYYY,[date]) as nvarchar(50))
from ArtistCalendar
You can use the DATENAME() function to get the name for a given month, which can be abbreviated like so:
SELECT LEFT(DATENAME(mm, GETDATE()),3) -- Output: 'Sep'
You can append the year using:
SELECT YEAR(GETDATE())
This should have to be converted to a string value to enable comparison with your supplied value. So you can do this:
SELECT LEFT(DATENAME(mm, GETDATE()),3) + '-'
+ CAST(YEAR(GETDATE()) AS NVARCHAR(4)) AS InputDate -- Output: Sep-2014
To check equality of a supplied value, e.g. Sep-2014:
SELECT LEFT(DATENAME(mm, GETDATE()),3) + '-'
+ CAST(YEAR(GETDATE()) AS NVARCHAR(4)) AS InputDate,
GETDATE() as FullDate,
CASE WHEN LEFT(DATENAME(mm, getdate()),3) + '-'
+ CAST(YEAR(GETDATE()) as nvarchar(4)) = 'SEP-2014'
THEN 'True'
ELSE 'False'
END as Equality
Ouptut
InputDate FullDate Equality
----------------------------------------------
Sep-2014 2014-09-15 14:35:57.427 True
To use with your table:
DECLARE #compareDate AS NVARCHAR(10)
SET #compareDate = 'Jan-2014' -- set this
SELECT LEFT(DATENAME(mm, [YOUR_COL]),3) + '-'
+ CAST(YEAR([YOUR_COL]) AS NVARCHAR(4)) AS InputDate,
[YOUR_COL]as FullDate,
CASE WHEN LEFT(DATENAME(mm, [YOUR_COL]),3) + '-'
+ CAST(YEAR([YOUR_COL]) as nvarchar(4)) = #compareDate
THEN 'True'
ELSE 'False'
END as Equality
From [YOUR_TABLE]
Just replace [YOUR_COL] with your date column and [YOUR_TABLE] with the table that holds the data column.
In Oracle SQL
You can do something like this
TO_CHAR(column_name, 'MON-YYYY')

Please help me with the group by clause

USE [MAS_CAN]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spHistorybyCalenderYear]--create a stored proc
#Year int = '2013'
AS
Begin
SET NOCOUNT ON
SELECT
isnull(round(l.UnitPrice*l.QuantityShipped,2),0) as SalesAmount,
isnull(round(l.unitCost*l.QuantityShipped,2),0) as CostAmount,
(case
when month(h.INVOICEDATE)=01 then '01'
when month(h.INVOICEDATE)=02 then '02'
when month(h.INVOICEDATE)=03 then '03'
when month(h.INVOICEDATE)=04 then '04'
when month(h.INVOICEDATE)=05 then '05'
when month(h.INVOICEDATE)=06 then '06'
when month(h.INVOICEDATE)=07 then '07'
when month(h.INVOICEDATE)=08 then '08'
when month(h.INVOICEDATE)=09 then '09'
when month(h.INVOICEDATE)=10 then '10'
when month(h.INVOICEDATE)=11 then '11'
when month(h.INVOICEDATE)=12 then '12'
END) as Period
FROM AR_INVOICEHISTORYHEADER h join AR_INVOICEHISTORYDETAIL l on (h.INVOICENO = l.INVOICENO)
Group by l.unitprice,l.unitcost,l.quantityShipped,h.invoicedate
order by Period
END
I would like to group it by period...Say I would like to see
Period SalesAmount CostAmount
01 22 19
02 24 25
Use this:
GROUP BY l.unitprice, l.unitcost, l.quantityShipped, CAST(MONTH(h.invoicedate) as varchar)
Also, you can get rid of that large case statement if you use this in its place:
SELECT
isnull(round(l.UnitPrice*l.QuantityShipped,2),0) as SalesAmount,
isnull(round(l.unitCost*l.QuantityShipped,2),0) as CostAmount,
CAST(MONTH(h.invoicedate) as varchar) as Period
FROM ...
As #Kaf mentioned, if you want Period to be 0 padded you can use either of these instead of the direct CAST:
right(100 + month(h.invoicedate),2)
left(convert(varchar, h.invoicedate, 10), 2)