I am having below formatted Date time value in my SQL Server database table.
2017-02-01 14:31:53.000
2017-09-01 14:54:11.000
I want to swap the Month & Date values like
2017-01-02 14:31:53.000
2017-01-09 14:54:11.000
Is there any way to achieve it?
There are multiple records with such format.
I tried using Excel to convert the same and create query. but it is not working.
As I wrote in my comment, DateTime are stored without display format.
If you want to select the dates in a specific format, you need to use either Format() (available in versions 2012 or higher) or CONVERT() (supports only predefined formats)
Now, assuming your desired format is yyyy-mm-dd hh:mi:ss, you can use convert with 120 style:
SELECT CONVERT(char(19), DateTimeColumn, 120) As FormattedDateTime
FROM TableName
/*
#formatString(varchar)
- the format string to use (Examples "dd mm yyyy", "mmm.dd.yy")
Description:
Formats a given date based on the format specified in #formatString
d - one digit day (when applicable)
dd- two digit day
ddd- short day name
dddd- long day name
m- one digit month (when applicable)
mm- two digit month
mmm- short month name
mmmm- long month name
yy- two digit year
yyyy- four digit year
*/
create function dbo.fnFormatDate
(
#inputDate datetime,
#formatString varchar(25)
)
returns varchar(20) as
begin
declare #returnValue varchar(25)
-- Declare local vairables
declare #formattedDate varchar(25),
#day varchar(20), #month varchar(20), #year varchar(20),
#dayFormat varchar(5), #monthFormat varchar(5), #yearFormat varchar(5)
set #dayFormat = ''
set #monthFormat = ''
set #yearFormat = ''
-- Convert the supplied date to day mon year (25 Jan 2008)
set #formattedDate = convert(varchar, #inputDate, 106)
-- If the format string contains a format for the day
if charindex('d', #formatString) > 0
-- Get the day format string
set #dayFormat = master.dbo.fn_pcre_replace(#formatString, '.*?(d{1,4}).*', '$1')
-- If the format string contains a format for the month
if charindex('m', #formatString) > 0
-- Get the month format string
set #monthFormat = master.dbo.fn_pcre_replace(#formatString, '.*? (m{1,4}|M{1,4}).*', '$1')
-- If the format string contains a format for the year
if charindex('y', #formatString) > 0
-- Get the year format string
set #yearFormat = master.dbo.fn_pcre_replace(#formatString, '.?(y{2,4}).', '$1')
-- Format the day value based on the format string for the day
select#day =
case #dayFormat
when 'dd' then master.dbo.fn_pcre_replace(#formattedDate, '^(\d+).*', '$1')
when 'ddd' then substring(datename(dw, #formattedDate), 1, 3)
when 'dddd' then datename(dw, #formattedDate)
else convert(varchar, day(#formattedDate))
end
-- Format the month value based on the format string for the month
select#month =
case #monthFormat
when 'mm' then master.dbo.fn_pcre_replace(convert(varchar, #inputDate, 101), '^(\d+)/.*', '$1')
when 'mmm' then master.dbo.fn_pcre_replace(#formattedDate, '\d+\s(\w+)\s\d+', '$1')
when 'mmmm' then datename(m, #formattedDate)
else convert(varchar, month(#formattedDate))
end
-- Format the year value based on the format string for the year
select#year =
case #yearFormat
when 'yy' then substring(convert(varchar, year(#formattedDate)), 3, 2)
else convert(varchar, year(#formattedDate))
end
set #returnValue = #formatString
-- If the day format was specified
if #dayFormat <> ''
-- Replace the day format string with the actual day value
set #returnValue = master.dbo.fn_pcre_replace(#returnValue, #dayFormat, #day)
-- If the month format was specified
if #monthFormat <> ''
-- Replace the month format string with the actual month
set #returnValue = master.dbo.fn_pcre_replace(#returnValue, #monthFormat, #month)
-- If the year format was specified
if #yearFormat <> ''
-- Replace the year format string with the actual year
set #returnValue = master.dbo.fn_pcre_replace(#returnValue, #yearFormat, #year)
-- Return the formated value
return #returnValue
end
Related
I have the following problem.
I have some dates with the following format '15122019' and I need it in this format 2019-12-15, which I already solved it in the following way.
select convert (date, Stuff(Stuff('15122018',5,0,'.'),3,0,'.'),104)
The real problem is when the dates come like this '3122019' the conversion can not be done because the length is shorter. Is ther e another way to do it? I've been trying to solve it for several hours. And another question, can this query be parameterized?
Try this:
DECLARE #date VARCHAR(20)
SET #date ='3122019'
IF(LEN(#date) = 8)
BEGIN
SET #date = Stuff(Stuff(#date,5,0,'.'),3,0,'.');
SELECT CONVERT(DATE, #date , 103);
END
ELSE IF(LEN(#date) = 7)
BEGIN
SET #date = Stuff(Stuff(#date,4,0,'.'),2,0,'.');
IF(ISDATE(#date)=1)
BEGIN
SELECT CONVERT(DATE, #date , 103);
END
ELSE
BEGIN
SET #date = Stuff(Stuff(#date,4,0,'.'),3,0,'.');
SELECT CONVERT(DATE, #date , 103);
END
END
ELSE IF(LEN(#date) = 6)
BEGIN
SET #date = Stuff(Stuff(#date,3,0,'.'),2,0,'.');
SELECT CONVERT(DATE, #date , 103);
END
You can add 0 to the left and take 8 chars with right. like RIGHT('0'+'15122018',8). it work with 15122018 and 3122018
select convert (date, Stuff(Stuff( RIGHT('0'+'15122018',8) ,5,0,'.'),3,0,'.'),104)
Such conversation can be achieved by:
Casting integer value to DATE using intermediate FORMAT transformation to a recognizable for conversation string pattern.
style 105 applied to match the input as dd-mm-yyyy
style 05 to match dd-mm-yy
SQL:
-- input format: dmmyyyy
SELECT CONVERT(DATE, FORMAT(3012019, '##-##-####'), 105)
-- result: 2019-01-03
-- input format: dmmyy
SELECT CONVERT(DATE, FORMAT(30119, '##-##-##'), 05)
-- result: 2019-01-03
This will work fine with a single (and double) digit day number, however, it indeed requires a double-digit month
Insert a column: received_by as text in the format of Day Month.
i.e. 25/06/2018 should be inserted as 25 June. The format dd/mm/yyyy should be converted into day month - whereby month should be written out.
You can use below select statement to get the desired return
select FORMAT(convert(datetime, '25/06/2018', 103), 'dd MMMM')
Or You can create the custom function in SQL server which will take a date in 'dd/mm/yyyy' format and return day and month as required. use below code to achieve the desired result.
create function GetDateDaynMonth(#date varchar(20))
returns varchar(20)
as
begin
declare #DaynMonth varchar (20)
SELECT #DaynMonth = FORMAT (convert(datetime, #date, 103), 'dd MMMM')
return #DaynMonth;
end
go
select dbo.GetDateDaynMonth('25/06/2018')
I want to get date from yyyy-mm-dd to yyyy-mm-dd in SQL.
Example: I have two parameter #startdate : 2015-12-28 and #enddate : 2016-01-02, and database in SQLServer, datatype is varchar(10)
DATE_ORDER
28-12-2015
30-12-1996
29-12-2016
30-12-1997
24-12-2015
27-12-1993
03-01-2016
01-01-1992
02-01-2016
etc...
Ok,now I want to get data from #startdate : 2015-12-28 and #enddate : 2016-01-02. I use SELECT * FROM TABLE_X WHERE DATE_ORDER >= #startdate AND DATE_ORDER <= #enddate . But the results are not what I expected. Here are the results I want
28-12-2015
30-12-1996
29-12-2016
30-12-1997
01-01-1992
02-01-2016
I think to solve this problem, I need to do two things :
First, get date range from #startdate to #enddate , in here 28/12/2015, 29/12/2015, 30/12/2015, 31/12/2015, 01/01/2016, 02/01/2016.
The second: get the date in database same in range 28/12, 29/12, 30/12, 31/12, 01/01, 02/01, ignoring the year.
Can you give me some ideas about this ?
Your actual format is "105-italian" find details here.
You can convert your existing VARCHAR(10)-values with this line to real datetime
SELECT CONVERT(DATETIME,YourColumn,105)
Next thing to know is, that you should not use BETWEEN but rather >=StartDate AND < NakedDateOfTheFollowingDay to check date ranges
So to solve your need Get date-range from 2015-12-28 to 2016-01-02 you might do something like this:
DECLARE #Start DATETIME={d'2015-12-28'};
DECLARE #End DATETIME={d'2016-01-02'};
SELECT *
FROM YourTable
WHERE CONVERT(DATETIME,YourDateColumn,105)>=#Start AND CONVERT(DATETIME,YourDateColumn,105)<#End+1
Attention Be aware, that the conversion lets your expression be not sargable. No index will be used.
Better was to store your date as correctly typed data to avoid conversions...
Try this query
SET DATEFIRST 1
DECLARE #wk int SET #wk = 2
DECLARE #yr int SET #yr = 2011
--define start and end limits
DECLARE #todate datetime, #fromdate datetime
SELECT #fromdate = dateadd (week, #wk, dateadd (YEAR, #yr-1900, 0)) - 4 -
datepart(dw, dateadd (week, #wk, dateadd (YEAR, #yr-1900, 0)) - 4) + 1
SELECT #todate = #fromdate + 6
;WITH DateSequence( Date ) AS
(
SELECT #fromdate AS Date
UNION ALL
SELECT dateadd(DAY, 1, Date)
FROM DateSequence
WHERE Date < #todate
)
--select result
SELECT * FROM DateSequence OPTION (MaxRecursion 1000)
So, after the 2nd or 3rd edit, it slowly becomes clear, what you want (i hope).
So you REALLY WANT to get the dates with the year beeing ignored.
As someone pointed out already, date-values are stored internally not as string, but as internal datatype date (whatever that is in memory, i don't know).
If you want to compare DATES, you cannot do that with ignorance of any part. If you want to, you have to build a NEW date value of day and month of given row and a hard coded year (2000 or 1 or whatever) for EVERY row.
SELECT * FROM TABLE_X WHERE convert(date,'2000' + substring(convert(char(8),convert(datetime, 'DATE_ORDER', 105),112),5,4),112) >= #startdate AND convert(date,'2000' + substring(convert(char(8),convert(datetime, 'DATE_ORDER', 105),112),5,4),112) <= #enddate
If your startdate and enddate go OVER sylvester, you have to do 2 queries, on from startdate to 1231, one from 0101 to enddate.
How do I convert a numbers in the columns with values like 20160912 into date formats of the form 09/12/2016 and order them by the dates in the date format.
You can use cast and convert built-in functions. Depending on what type is 20160912 you can do following.
A) int
declare #d int=20160912
select convert(varchar(20),convert(date,convert(varchar,#d)),101)
--step by step
declare #dStr varchar(20)
set #dStr = convert(varchar,#d) --'20160912'
-- or = cast(#d as varchar)
declare #dDate date --or datetime
set #dDate = convert(date, #dStr) --2016-09-12 (this is external representation)
--show in MM/dd/yyyy format
select convert(varchar(20), #dDate, 101) --magic 101 for MM/dd/yyyy
--09/12/2016
B) varchar just omit innermost conversion
A SQL Server application we use (accpac) represents dates as an 8 digit decimal in ISO format (example: today's date is 20100802)
I need to add one month to this. I've found a way to do it, but there must be a better way.
The steps of my solution are:
declare #accpacDate as decimal
set #accpacDate = 20100101
declare #date1 as date
declare #date2 as date
set #date1=cast(CAST(#accpacDate as varchar(8)) as datetime) /*get the starting value as a date */
set #date2=DATEADD(month,1,#date1)
select CONVERT(varchar(8),#date2,112) as aVarchar
select convert(decimal,CONVERT(varchar(8),#date2,112)) as aDecimal
SELECT CONVERT(VARCHAR(8),DATEADD(MONTH,1,CONVERT(VARCHAR(8),20100802,112)),112)
It seems about right what you are doing.
String and Date manipulation is pretty core in SQL, no fancy wrappers for auto-converting and manipulating date formats (accpac, memories, shiver).
You could write that into a user function, to add days to a accpac date, and return the result:
create function accpacadd
( #accpacdate decimal,
#days int)
RETURNS decimal
AS BEGIN
declare #date1 as datetime
set #date1=cast(CAST(#accpacDate as varchar(8)) as datetime) /*get the starting value as a date */
set #date1=DATEADD(day, #days, #date1)
return convert(decimal, CONVERT(varchar(8), #date1, 112))
END
So then you can just call it with min code:
select dbo.accpacadd(20100102, 5)
select dbo.accpacadd(20100102, -5)
Gives 20100107 and 20091228 respectively