Converting various date formats into a single date object - sql-server

I have a table in SQL Server 2008 R2 with a nvarchar(50) column which stores different formats of date such as 'dd/mm/yyyy', 'mm/dd/yyyy', 'yyyy-mm-dd', etc.
Now I am writing a procedure that will convert/cast this column as a date type. Something as below:
SELECT CONVERT(DATE, Column1) as [Date]
But due to varying formats of date I tend to get the following error in my C# application:
"Conversion failed when converting date and/or time from character string"
I know of a function TRY_CONVERT and TRY_PARSE which can solve this problem but it's only available in SQL Server 2012 and above. Any workaround for this in SQL Server 2008?

Related

SQL Server stored procedure passing date parameters

ALTER PROCEDURE [dbo].[AccountsData]
#Start_Date datetime,
#End_Date datetime
AS
BEGIN
SET NOCOUNT ON;
SELECT
a.Customer_AC_No, a.Customer_Name, a.Product_Code,
a.Product_Description, a.Sales_Person, c.HSID
FROM
(SELECT
Customer_AC_No, Customer_Name, Product_Code,
Product_Description, Sales_Person
FROM
View_Sales_Details
WHERE
([Week Ending] >=' #Start_Date') AND ([Sales Value] > 0)
GROUP BY
Customer_AC_No, Product_Code, Product_Description,
Customer_Name, Sales_Person) AS a
LEFT JOIN
(SELECT
Customer_AC_No, Product_Code
FROM
View_Sales_Details
WHERE
([Week Ending] >= '#End_Date') AND ([Sales Value] > 0)
GROUP BY
Customer_AC_No, Product_Code) AS b ON a.Customer_AC_No = b.Customer_AC_No
AND a.Product_Code = b.Product_Code
INNER JOIN
Hubspot.dbo.View_BPA_Cust_Data AS c ON a.Customer_AC_No = c.CustomerNo COLLATE Latin1_General_100_CI_AS
WHERE
b.Customer_AC_No IS NULL
ORDER BY
a.Customer_AC_No, a.Product_Code ASC
END
I am trying to pass the above date parameters to the SQL Server stored procedure above, but I keep getting this error
Msg 241, Level 16, State 1, Procedure AccountsData, Line 52
Conversion failed when converting date and/or time from character string.
Can some one please help. WeekEnding date is also in datetime format. Thanks
There are many formats supported by SQL Server for specifying a date&time as a string literal - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible.
So in your case, either switch to using DATE as your parameter datatype (since you obviously don't use the time portion):
ALTER PROCEDURE [dbo].[AccountsData]
#Start_Date DATE,
#End_Date DATE
and then execute your stored procedure like this:
EXEC [dbo].[AccountsData] '2019-05-11', '2020-06-10'
or use this format to support DATETIME if you insist on keeping that:
EXEC [dbo].[AccountsData] '2019-05-11T00:00:00', '2020-06-10T00:00:00'
Your have an error in your select. You have change your query like this
DATEPART(wk, Ending)>=DATEPART(wk, #Start_Date) AND ([Sales Value] > 0)
DATEPART(wk, Ending)>=DATEPART(wk, #End_Date) AND ([Sales Value] > 0)

Error in SQL Server Agent: "the conversation of a varchar data type to a datetime data type resulted in an out-of-range.""

I created a small script that works in SQL Server Management Studio, then I created a SQL Server Agent job with that same script; but after I run it, I get an error:
The conversation of a varchar data type to a datetime data type resulted in an out-of-range
I fixed the problem by change the format of date to ISO 8601, but I don't release how my first script works on SSMS and not in SQL Server Agent.
First script:
declare #teste datetime
set #teste = '31/12/2099 00:00:00'
select #teste
Fix error:
declare #teste datetime
set #teste = '20991231 00:00:00'
select #teste
This is one reason why using unambiguous formats are so important when using date(time) datatypes. The only formats that an unambgious in SQL Server, regardless of language and datatype are the formats yyyyMMdd and yyyy-MM-ddThh:mm:ss.
For the date '31/12/2099 00:00:00' and the language your Login is using it appears that SQL Server is interpreting the value as the 12th day, of the 31st month, of the year 2099. There aren't 31 months in the year, and hence the error. (DB<>Fiddle). It's worth noting that date (and the other "new" datetime data types) behave differently and also can unambiguously understand the format yyyy-MM-dd; notice in this DB<>fiddle the difference in the values for the datetime values simply due to the language setting.
As you can see, the solution is to use a unambiguous format. So, as you're using a date and time, I would suggest the string '2099-12-31T00:00:00'.

Conversion failed when converting date and/or time from character string in MS SQL Server 2017

I am a newbie to MS SQL Server, I get the error
Conversion failed when converting date and/or time from character string
running the following query:
CREATE TABLE DateVals
(
dt datetime,
t time,
dt2 datetime2,
dts datetimeoffset
);
GO
INSERT INTO DateVals (dt, t, dt2, dts)
VALUES ('2011-01-01 23:10:10.003', '23:10:10.003', '2011-01-01 23:10:10.003', '2011-01-01 23:10:10.003 +02.00');
GO
Could you tell me why I get this error?
PS. My OS language is Polish
Your query is correct, just need a colon instead of a comma in the datetimeoffset when you use +02:00.
INSERT INTO DateVals (dt, t, dt2, dts)
VALUES ('2011-01-01 23:10:10.003', '23:10:10.003', '2011-01-01 23:10:10.003', '2011-01-01 23:10:10.003 +02:00');
Instead of
INSERT INTO DateVals (dt, t, dt2, dts)
VALUES ('2011-01-01 23:10:10.003', '23:10:10.003', '2011-01-01 23:10:10.003', '2011-01-01 23:10:10.003 +02.00');
Converting a string literal into a DATETIME column is quite an adventure - and DATETIME is very peculiar about what formats are supported.
The best way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
So in your case, try either:
INSERT INTO DateVals (dt, t, dt2, dts)
VALUES ('2011-01-01T23:10:10', '23:10:10.003', '2011-01-01 23:10:10.003', '2011-01-01 23:10:10.003 +02:00');
(you also need to use a : in the +02:00 moniker for the DATETIMEOFFSET - not a dot or comma)
or make dt in your table a column of type DATETIME2(n) (instead of DATETIME).
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible

SQL Server - Calculate Age from date of birth in Varchar

Using SQL Server 2008 R2
I have a database of my friend's project. He used varchar to store date of birth of members because he was getting errors parsing entries to date. I want to show the age using a procedure code.
the format of date stored in mm/dd/yyyy where today's date is stored as 3/4/2016 . I wanted to use DATEDIFF function but it is not a good option with varchar.
Create procedure spCalculateAge
#dob varchar(10)
as
Begin
Select DATEDIFF(year,Convert(date,#dob),getdate()) as Age
End
I used this and it worked. Before it was giving conversion error but opening and closing SQL Server caused it to work.

Format date of filters and results on SQL Server

I'm in a trouble with the format of dates on my queries.
In SQL Server when I execute the following query:
select *
from users
where register_date >= '2015-03-17'
It throws me a cast conversion error.
But if I do execute the following query:
select *
from users
where register_date >= '2015-17-03'
It returns me the correct data, BUT when I see the the register_date column, it gives me the dates as 'YYYY-MM-DD' format...so it's a little confusing...
How can I configure SQL Server to work always with "YYYY-MM-DD" format, on filters and results?
SQL Server doesn't store a DateTime in any string format - it's stored as an 8 byte numerical value.
The various settings (language, date format) only influence how the DateTime is shown to you in SQL Server Management Studio - or how it is parsed when you attempt to convert a string to a DateTime.
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible
So in your concrete case - what if you run this query:
select *
from users
where register_date >= '20150317'
Do you get the expected results?
Your Date format in SQL SERVER is 'YYYY-DD-MM' that's why you are getting cast conversion error. For searching you must give the date with this exact format.
But In case of getting result you can use SQL DATE FORMAT and retrieve date in any format e.g
SELECT DATE_FORMAT(users.register_date ,'%Y-%d-%m') AS date FROM users
Result will be : 2015-17-03

Resources