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')
Related
I have a column in format as
yyyyMM
in a table and a column of date as yyyyMMdd in another table,
which is month end value.
I want to compare both in a query where I can't perform any action on 2nd one.
is there any way to convert yyyyMM to end of month as yyyyMMdd?
It's a total hack, but you can do this:
DECLARE #BadDate CHAR(6) = '202004';
SELECT EOMONTH(#BadDate + '01');
Answer is:
2020-04-30
You can also try the following:
DECLARE #d CHAR(6) = '202004';
select format(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#d+'01')+1,0)), 'yyyyMMdd')
db<>fiddle.
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
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.
I am trying to get data after year 2012.
Date is saved in nvarchar format in a table. For example: 12/31/2010
Column also has some other values like 'Confidential', I don't want this row.
I am trying a query (shown below) but it is not succeed :-
select *
from tbl_ProductionWells
where CONVERT(NVARCHAR(10), wellstatusdate, 103) > CONVERT(NVARCHAR(10), '01/01/2012', 103)
Edited :-
I tried this :-
SELECT *
FROM tbl_ProductionWells
WHERE DATEPART(YEAR, CAST(wellstatusdate AS date)) > 2012
But it is giving an error (shown below), This column also has some text values like 'not available','Confidential' .. :-
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Note:- I can't change column datatype as it also contains some other texts.
Thanks in advance
First of all: Store date values in DATE columns, datetimes in DATETIME2 columns. Always choose proper data type for your data
You have to convert your NVARCHAR to DATE, then compare it to 2012-01-01
OR you can extract the 'year' part of your string.
SELECT *
FROM tbl_ProductionWells
WHERE CONVERT(DATE, wellstatusdate) >= '2012-01-01'
The best choice is to change your column's data type to DATE. After that, you can do lots of magicial things with those values. Store the 'Confidental' flag in another column.
EDIT
Some additional info:
Please note, that the STRING -> DATE conversion depends on the current session's language.
Run this batch to see the difference:
DECLARE #DateAsChar VARCHAR(32) = '01/02/12';
SET LANGUAGE us_english
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
SET LANGUAGE Hungarian
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
SET LANGUAGE Deutsch
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
How about:
WITH cte
AS ( SELECT *
FROM tbl_ProductionWells
WHERE ISDATE(wellstatusdate) = 1
)
SELECT *
FROM cte
WHERE DATEPART(YEAR, CAST(wellstatusdate AS DATE)) > 2012
Select all data from the table that is a date using IsDate, then work with that dataset only.
SELECT * FROM
(SELECT * FROM tbl_ProductionWells WHERE ISDATE(wellstatusdate) = 1)
WHERE CAST(wellstatusdate as Date) > #YOURDATE
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