I have a nvarchar column and it is containing dates in different formats like
'2/1/2012',
'2/2/12',
'20 01 12',
'20 03 2012',
'20.01.12',
'30.04.2012',
'20jan 12',
'20-MARCH-2012',
'22MARCH2012',
'23 may 2012',
'23-MAR-2012',
'26MAR-2012',
'27TH JAN 4660',
'CHL. Date- 30.01.2012',
'APRIL/12/2012',
'N/A',
'DT.:5/1/12',
Now I want to insert the data from this column to date column in format dd/mm/yyyy but not able to do that as it always give error
Conversion failed when converting date and/or time from character string
Please help if anyone knows how to convert this column to date column with all specified values defined above
To convert a nvarchar column to a DATETIME, you will need to use the CONVERT function in T-SQL.
This function supports a set of "styles" - all of which are very well documented on MSDN.
If your source string matches one of those defined styles, you can use the appropriate CONVERT to get a DATETIME from your string. There is however no "magic" in T-SQL to recognize which conversion style would match your string - that's entirely up to you.
With this query here, you can list out all the CONVERT styles for T-SQL:
DECLARE #Today DATETIME = GETDATE()
SELECT
Default_100 = CONVERT(VARCHAR(50), #Today, 100),
US_101 = CONVERT(VARCHAR(50), #Today, 101),
ANSI_102 = CONVERT(VARCHAR(50), #Today, 102),
BritishFrench_103 = CONVERT(VARCHAR(50), #Today, 103),
Germany_104 = CONVERT(VARCHAR(50), #Today, 104),
Italian_105 = CONVERT(VARCHAR(50), #Today, 105),
Style106 = CONVERT(VARCHAR(50), #Today, 106),
Style107 = CONVERT(VARCHAR(50), #Today, 107),
Style108 = CONVERT(VARCHAR(50), #Today, 108),
Default_with_ms_109 = CONVERT(VARCHAR(50), #Today, 109),
USA_110 = CONVERT(VARCHAR(50), #Today, 110),
Japan_111 = CONVERT(VARCHAR(50), #Today, 111),
ISO_112 = CONVERT(VARCHAR(50), #Today, 112),
Europe_default_with_ms_113 = CONVERT(VARCHAR(50), #Today, 113),
Style114 = CONVERT(VARCHAR(50), #Today, 114),
ODBC_canonical_120 = CONVERT(VARCHAR(50), #Today, 120),
ODBC_canonical_with_ms_121 = CONVERT(VARCHAR(50), #Today, 121),
ISO_8601_126 = CONVERT(VARCHAR(50), #Today, 126),
ISO_8601_with_timezone_Z_127 = CONVERT(VARCHAR(50), #Today, 127),
Hijri_130 = CONVERT(VARCHAR(50), #Today, 130),
Hijri_131 = CONVERT(VARCHAR(50), #Today, 131)
If your source string does not match any of the predefined styles - you're out of luck, and it'll take a lot more string parsing and T-SQL code to convert your string to a valid DATETIME.
If your string matches one of the styles, you can convert it like this:
DECLARE #Date DATETIME
SET #Date = CONVERT(DATETIME, '30.04.2012', 104)
The best way is to write a function that takes the string and converts it to a non ambiguous date string (yyyy-mm-dd). This can then be converted to a datetime. There's now magical way of converting various formats to date format.
Related
I am attempting to set the default start date of a report to the previous business day, which is
dateadd(dd,-1,getdate())
on all days except Monday when it is
dateadd(dd,-3,getdate())
Prior to this report being converted to an SSRS report this was handled in the proc with the query
declare #startDate datetime =
(
select
case
when DATENAME(dw, CONVERT(date, getdate())) = 'Monday' then cast(Convert(date, dateadd(DD,-3,CONVERT(date, getdate()))) as nvarchar(100))
else cast(Convert(date, dateadd(DD,-1,#today)) as nvarchar(100))
end
)
How would I implement this conditional start date using an SSRS =IIF statement?
Thanks
Upon more research I've discovered the method to do this is:
=DateAdd(DateInterval.Day
, Switch(DatePart(DateInterval.WeekDay, Today()) = 2, -3
,DatePart(DateInterval.WeekDay, Today()) = 1, -2
,True, -1)
, Today())
I would use switch personally:
=Switch(
WeekdayName(Weekday(today))="Monday",dateadd(DateInterval.Day,-3,today),
True,dateadd(DateInterval.Day,-1,today)
)
I am getting above error can anyone please help what is the issue with the code...
P.YKey BETWEEN YEAR('''+ CONVERT(VARCHAR(50), #BDate, 103) +''')
AND YEAR('''+ CONVERT(VARCHAR(50), #eDate, 103) +''')
AND P.DCreation BETWEEN '''+ CONVERT(VARCHAR(50), #BDate, 103) +'''
AND '''+ CONVERT(VARCHAR(50), #eDate, 103) +''''
What is the type of #BDate, #eDate?
Update:
As the type of the two variables are DATETIME, the conversion is not necessary.
P.YKey BETWEEN YEAR(#BDate)
AND YEAR(#eDate)
AND P.DCreation BETWEEN #BDate
AND #eDate
as it seems that you are interested on the creation date only, not the time, I would also cast the datetimes to date. So assuming that DCreation is datetime too:
P.YKey BETWEEN YEAR(#BDate)
AND YEAR(#eDate)
AND cast(P.DCreation as date) BETWEEN cast(#BDate as date)
AND cast(#eDate as date)
Microsoft SQL 2008 (using Visual Studio 2010 to build and test query).
Query function: This query is going to be run via batch file in Windows Task Scheduler. The goal is to be able to create a CSV file every month.
My query:
SELECT TYPE, DATEX, TIME, STREET, CROSS_ST, XCOORD, YCOORD
FROM INCIDENT
WHERE (TYPE = '644') OR
(TYPE = '459') OR
(TYPE = 'HS') OR
(TYPE = '484') OR
(TYPE = '487') OR
(TYPE = '488') OR
(TYPE = '10851') OR
(TYPE = '187') OR
(TYPE = '211') OR
(TYPE = '245') OR
(TYPE = '451')
ORDER BY DATEX
I am trying to sort the 'DATEX' column (which is in datetime format) between 'today's date' and '30 days ago'
I have tried all of these statements and none of them work:
(DATEX < DATEADD(month, - 1, GETDATE()))
DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH)),
(
CONVERT(varchar, DATEX, 110) AS DATE,
DATEX CONVERT(varchar, DATEADD(d,-30,GETDATE()), 23)
)
*ERROR INTERVAL is not recognized
AND DATEX BETWEEN DATEADD(mm,-1,GETDATE()) AND DATEADD(mm,1,GETDATE())
*error unrecognized syntax 1
=DateAdd("d", -7, Today()) *Today is not a recognized function
where date_col > DATEADD(day,-7,SYSDATETIME())
*unrecognized syntax near 'Where'
where DATEDIFF(day,date_col,SYSDATETIME()) < 7
*error near 'WHERE'
DATEX Dte < DATEADD(month, -2, GETDATE())
*an expression of non-Boolean type specified
AND (DATEX BETWEEN ({ fn CURDATE() }, 30) AND { fn CURDATE() })
*incorrect syntax near ','
What is the correct syntax for Microsoft SQL query to sort a table 'incident' between 'today's date' and '30 days ago'?
Please note that simply using Between 'YYYY-MM-DD' and 'YYYY-MM-DD' is not helpful because I would need to manually change the dates to run the query. I want to automate it to create a CSV file every month.
Instead of throwing everything at the wall and seeing what sticks, I strongly recommend reading the vendor's documentation. Microsoft SQL Server has extremely comprehensive and readable documentation, even among RDBMSs, both on the web and if you install the fantastic SQL Server Books Online.
As to your issue, you'll need to use DATEADD(). The problem, however, is that datetime fields and GETDATE() have a time component, and you need to account for that.
So, one of the keys you'll need to know, is how to strip the time from a datetime. If you're on SQL Server 2008 R2 and higher, you can do this:
CAST(GETDATE() AS DATE)
But that doesn't work on SQL Server 2008 and earlier. Instead, you need to use this:
DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
If you know that DATEX is never in the future, you can use this:
SELECT TYPE, DATEX, TIME, STREET, CROSS_ST, XCOORD, YCOORD
FROM INCIDENT
WHERE TYPE IN ('644','459','HS','484','487','488','10851','187','211','245','451')
AND DATEX >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) - 30, 0)
ORDER BY DATEX
Which is, "DATEX is on or after midnight 30 days ago."
Now, if DATEX might be in the future, but it always has a zero time value, you can use this:
SELECT TYPE, DATEX, TIME, STREET, CROSS_ST, XCOORD, YCOORD
FROM INCIDENT
WHERE TYPE IN ('644','459','HS','484','487','488','10851','187','211','245','451')
AND DATEX BETWEEN DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) - 30, 0) AND GETDATE()
ORDER BY DATEX
Which is, "DATEX is on or after midnight 30 days ago and on or before right now." On the other hand, if DATEX might be in the future and will have a non-zero time component, you should use this:
SELECT TYPE, DATEX, TIME, STREET, CROSS_ST, XCOORD, YCOORD
FROM INCIDENT
WHERE TYPE IN ('644','459','HS','484','487','488','10851','187','211','245','451')
AND DATEX >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) - 30, 0)
AND DATEX < DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) + 1, 0)
ORDER BY DATEX
This is "DATEX is on or after midnight 30 days ago and before midnight tomorrow." It's easier to refer to "before midnight tomorrow" because datetime can have fractional seconds.
You can use Dateadd Function also remove the multiple OR conditions and use IN clause
SELECT TYPE, DATEX, TIME, STREET, CROSS_ST, XCOORD, YCOORD
FROM INCIDENT
WHERE DATEX BETWEEN DATEADD(dd,-30,GETDATE()) AND GETDATE()
AND TYPE in ('644','459','HS','484','487','488','10851','187','211','245','451')
ORDER BY DATEX
This should work for your condition.
WHERE DATEX BETWEEN GETDATE()-30 AND GETDATE()
it will minus 30 days off from todays date
Your query should be something like this
SELECT TYPE, DATEX, TIME, STREET, CROSS_ST, XCOORD, YCOORD
FROM INCIDENT
WHERE DATEX > DATEADD(dd, -30, CAST(CAST(GETDATE() AS INT) AS DATETIME)) AND
((TYPE = '644') OR
(TYPE = '459') OR
(TYPE = 'HS') OR
(TYPE = '484') OR
(TYPE = '487') OR
(TYPE = '488') OR
(TYPE = '10851') OR
(TYPE = '187') OR
(TYPE = '211') OR
(TYPE = '245') OR
(TYPE = '451'))
ORDER BY DATEX
Here you can find a working demo
Hope this helps
Could any one help me convert this Microsoft access query to Tsql 2008:
SELECT
dbo_Invoiceable__c.NAME AS Invoiceable,
dbo_Invoiceable__c.Payment_is_due__c,
dbo_Invoiceable__c.Day_Due__c,
DATE () AS [Invoice Date],
DateSerial(Year(DATE ()), Month(DATE ()), [Day_Due__c])
AS [On a day of the month],
DateAdd("d", [day_due__c], DATE ())
AS [In a given number of days],
DateAdd("d", [day_due__c] - 1, DateAdd("m", 1, DateSerial(Year(DATE ()), Month(DATE ()), 1)))
AS [No of days after EOM],
IIf([Payment_is_due__c] = "In a given number of days", [In a given number of days], "") & IIf([Payment_is_due__c] = "On a day of this month", [On a day of the month], "") & IIf([Payment_is_due__c] = "No of days after EOM", [No of days after EOM], "")
AS [Due Date]
FROM dbo_Invoiceable__c;
I have tried this:
SELECT *,
CASE
WHEN [Payment_is_due__c] = 'In a given number of days' THEN [In a given number of days] ELSE ''
END + CASE
WHEN [Payment_is_due__c] = 'On a day of this month' THEN [On a day of the month] ELSE ''
END + CASE
WHEN [Payment_is_due__c] = 'No of days after EOM' THEN [No of days after EOM] ELSE ''
END AS [Due Date]
FROM (SELECT [SalesForce_LIVE.dbo.Invoiceable__c].[Name] AS Invoiceable,
[SalesForce_LIVE.dbo.Invoiceable__c].[Payment_is_due__c],
[SalesForce_LIVE.dbo.Invoiceable__c].[Day_Due__c],
CONVERT (DATETIME, CONVERT (VARCHAR, GETDATE(), 1), 1) AS [Invoice Date],
dbo.DateSerial(Year(CONVERT (DATETIME, CONVERT (VARCHAR, GETDATE(), 1), 1)), Month(CONVERT (DATETIME, CONVERT (VARCHAR, GETDATE(), 1), 1)), [Day_Due__c]) AS [On a day of the month],
DATEADD(d, [day_due__c], CONVERT (DATETIME, CONVERT (VARCHAR, GETDATE(), 1), 1)) AS [In a given number of days],
DATEADD(d, [day_due__c] - 1, DATEADD(m, 1, dbo.DateSerial(Year(CONVERT (DATETIME, CONVERT (VARCHAR, GETDATE(), 1), 1)), Month(CONVERT (DATETIME, CONVERT (VARCHAR, GETDATE(), 1), 1)), 1))) AS [No of days after EOM]
FROM SalesForce_LIVE.dbo.Invoiceable__c) AS Nested1;
But still cant get the dateserial working in Tsql
DECLARE #firstdayofmonth datetime;
DECLARE #lastdayofmonth datetime;
SET #firstdayofmonth = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0);
SET #lastdayofmonth = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0));
SELECT *,
CASE WHEN [Payment_is_due__c]='In a given number of days' THEN [In a given number of days] ELSE '' END +
CASE WHEN [Payment_is_due__c]='On a day of this month' THEN [On a day of the month] ELSE '' END +
CASE WHEN [Payment_is_due__c]='No of days after EOM' THEN [No of days after EOM] ELSE '' END AS [Due Date]
FROM (SELECT SalesForce_LIVE.dbo.Invoiceable__c.[Name] AS Invoiceable, SalesForce_LIVE.dbo.Invoiceable__c.[Payment_is_due__c], SalesForce_LIVE.dbo.Invoiceable__c.[Day_Due__c],
CONVERT(DATETIME,CONVERT(VARCHAR,GETDATE(),1),1) AS [Invoice Date],
DATEADD(DAY,[day_due__c],#firstdayofmonth-1) AS [On a day of the month],
DATEADD(DAYOFYEAR,[day_due__c],CONVERT(DATETIME,CONVERT(VARCHAR,GETDATE(),1),1)) AS [In a given number of days],
DATEADD(DAY,[day_due__c],#lastdayofmonth) AS [No of days after EOM]
FROM SalesForce_LIVE.dbo.Invoiceable__c
) AS Nested1
In sql, how to get the starting and ending date of week for the particular month. Can you help me.
The following will work whatever you consider the first day of the week (sunday, monday etc), just ensure you use SET DATEFIRST if you want to change from the default. SET DATEFIRST 1 will make the first day of the week monday.
SELECT DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)) [WeekStart],
DATEADD(DAY, 7 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)) [WeekEnd]
EDIT
I have just re-read you request and I think you may be after something different to what I have given above. If you want the day of the week of the first and last of the month this will do the trick:
SELECT DATENAME(WEEKDAY, DATEADD(DAY, 1 - DATEPART(DAY, GETDATE()), GETDATE())) [FirstDayOfMonth],
DATENAME(WEEKDAY, DATEADD(DAY, - DATEPART(DAY, DATEADD(MONTH, 1, GETDATE())), DATEADD(MONTH, 1, GETDATE()))) [LastDayOfMonth]
Your requirement is unclear: what do you consider to be the first and last days of a week? Sunday and Saturday? Monday and Friday? Monday and Sunday? But the best solution for many date-related queries is to create a calendar table. That gives you the ability to easily set the first and last days of weeks, months and years according to your definition and even in multiple formats if necessary.
This is especially useful if you work with concepts like financial years, business days, and so on where the definitions vary by country and even company. It is also the easiest solution when there are exceptions to your logic, e.g. the first week of the year has different rules than a 'normal' week.
With a calendar table you could pre-populate the first and last days of the week and then your query could be something like this:
-- first/last days stored as dates in their own columns
select FirstDayOfThisWeek, LastDayOfThisWeek
from dbo.Calendar
where BaseDate = #SomeDate
-- first/last days stored as bit flags
select max(BaseDate)
from dbo.Calendar
where BaseDate <= #SomeDate and IsFirstDayOfWeek = 0x1
Below is a case statement you can use to create a Weekbegin for your date value. It will make your weeks start on Monday or Tuesday or Wed... etc. dependant on what day of the week you have set as #pDate.
Create parameters
DECLARE #pDate Date = NULL --Replace with your date, which will also be the first day of the week
DECLARE #pDatePart SMALLINT = DATEPART(dw, #pDate)
Then put this case Statement after your select
CASE
WHEN DATEPART(dw, CAST(DATEVALUE AS DATE)) BETWEEN #pDatePart AND 7 THEN DATEADD(d, (DATEPART(dw, CAST(DATEVALUE AS DATE))*-1)+#pDatePart, CAST(DATEVALUE AS DATE))
WHEN DATEPART(dw, CAST(DATEVALUE AS DATE)) BETWEEN 1 AND #pDatePart-1 THEN DATEADD(d, (DATEPART(dw, CAST(DATEVALUE AS DATE))*-1)+(#pDatePart-7), CAST(DATEVALUE AS DATE))
END
AS DynamicWeekBegin
You can always get the final date of the week, just by using dateadd(d, 6, THE CASE STATEMENT)
Here i given
Week,month,quarter,half year,year start and end date.
Select CONVERT(varchar(50), GETDATE(),105) 'GETDATE' ,
CONVERT(varchar(50), DATEADD(DAY, 2 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)),105) [WeekStart],
CONVERT(varchar(50),DATEADD(DAY, 8 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)) ,105)[WeekEnd],
CONVERT(varchar(50),DATEADD(dd, -DAY(getdate()) + 1, getdate()),105) MonthStart,
CONVERT(varchar(50),DATEADD(dd, -DAY(DATEADD(mm, 1, getdate())), DATEADD(mm, 1, getdate())),105) MonthStart,
CONVERT(varchar(50), DATEADD(q, DATEDIFF(q, 0, GETDATE()), 0),105) AS 'QStart Date',
CONVERT(varchar(50), DATEADD(d, -1, DATEADD(q, DATEDIFF(q, 0, GETDATE()) + 1,0)),105) AS 'QEnd Date',
CONVERT(varchar(50), CAST(CAST(((((MONTH(GETDATE()) - 1) / 6) * 6) + 1) AS VARCHAR) + '-1-' + CAST(YEAR(GETDATE()) AS VARCHAR) AS DATETIME),105) StartOfHalfYear,
CONVERT(varchar(50), CAST(CAST(((((MONTH(GETDATE()) - 1) / 6) * 6) + 6) AS VARCHAR) + '-1-' + CAST(YEAR(GETDATE()) AS VARCHAR) AS DATETIME),105)EndOfHalfYear,
CONVERT(varchar(50), DATEADD(yy, DATEDIFF(yy,0,getdate()), 0),105) AS StartOfYear,
CONVERT(varchar(50), DATEADD(yy, DATEDIFF(yy,0,getdate()) + 1, -1),105) AS EndOfYear