Conversion of Date in SQL Server - sql

I am trying to make a comparison on the basis of CreatedDate but it gives me an error like
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value
here is my query as #startdate and #endDate are my parameters for the Stored procedure.
declare #startDate as varchar(100) = null
declare #endDate as varchar(100) = null
set #startDate = '01/11/2016'
set #endDate = '30/11/2016'
SELECT CreatedDate FROM Table1
WHERE HCCreatedDate BETWEEN
CONVERT(Datetime, ISNULL(#startDate,''), 103)
AND CONVERT(Datetime, ISNULL(#endDate,''), 103)

Please convert the HCCreatedDate column as below
declare #startDate as varchar(100) = null
declare #endDate as varchar(100) = null
set #startDate = '01/11/2016'
set #endDate = '30/11/2016'
SELECT
CreatedDate
FROM
Table1
WHERE
CONVERT(DATETIME,HCCreatedDate,103) BETWEEN CONVERT(DATETIME, ISNULL(#startDate,''), 103) AND CONVERT(DATETIME, ISNULL(#endDate,''), 103)

Also Conver your column into Datetime. and try again
declare #startDate as varchar(100) = null
declare #endDate as varchar(100) = null
set #startDate = '01/11/2016'
set #endDate = '30/11/2016'
SELECT CreatedDate FROM Table1
WHERE CONVERT(DATETIME, HCCreatedDate), 103)BETWEEN
CONVERT(DATETIME, ISNULL(#startDate,''), 103)
AND CONVERT(DATETIME, ISNULL(#endDate,''), 103)

Related

How to convert Datetime to String then String to Datetime

This is the line.
DECLARE #Duration DATETIME = '2019-01-12'
DECLARE #DateFrom DATETIME = CONVERT(DATETIME, DATEADD(dd, -90, CONVERT(VARCHAR(10), #Duration)))
SELECT #DateFrom
This is the error message
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
and the sql results is NULL but 1 row affected.
Stop using CONVERT() to begin with, you don't need it!
DATEADD() can take in a DATETIME variable as-is and return a DATETIME:
DECLARE #Duration DATETIME = '2019-01-12'
DECLARE #DateFrom DATETIME = DATEADD(dd, -90, #Duration)
SELECT #DateFrom
It can also take in a date/time string literal and returns a DATETIME:
DECLARE #DateFrom DATETIME = DATEADD(dd, -90, '2019-01-12')
SELECT #DateFrom
Using DATEADD function, your query would be something like this depending on what you afforded in your problem :
DECLARE #Date datetime2 = '2011-09-23 15:48:39.2370000'
SELECT DATEADD(day,-90,#Date)
DECLARE #DateVariable DATETIME
SET #DateVariable = '2019-01-12'
DECLARE #DateFrom DATETIME = CONVERT(DATETIME, DATEADD(dd, -90, CONVERT(VARCHAR(10), #DateVariable,103)))
SELECT #DateFrom
I find an answer here. The problem is with the time zone setting. Specify in other formats like mm/dd/yyyy (usually works).
SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

Convert varchar column to datetime in sql server

I have a table with following definition and data.
Definition:
CREATE TABLE [dbo].[TestTB]
(
[CREATEDATE] [nvarchar](50) NULL
) ON [PRIMARY]
Data:
10/9/2014
1/26/2015
2/16/2015
When I run the query:
Select
CAST(CREATEDATE AS DATETIME) as CREATEDATE
FROM
[dbo].[TestTB]
It is throwing error:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
The above does not work even after running
SET DATEFORMAT dmy
However the following query works fine
DECLARE #data nvarchar(50)
SET #data = ' 10/9/2014 '
Select CAST(#data as DateTime)
Above query returns: 2014-10-09 00:00:00.000
How do I convert a date string (of mm/dd/yyyy format) stored in a column to datetime?
First, if your table column is "DateTime" type than it will save data in this format "2014-10-09 00:00:00.000" no matter you convert it to date or not. But if not so and if you have SQL Server version 2008 or above than you can use this,
DECLARE #data nvarchar(50)
SET #data = '10/9/2014'
IF(ISDATE(#data)>0)
BEGIN
SELECT CONVERT(DATE, #data)
END
Otherwise
DECLARE #data nvarchar(50)
SET #data = '10/9/2014'
IF(ISDATE(#data)>0)
BEGIN
SELECT CONVERT(DATETIME, #data)
END
To Insert into table
INSERT INTO dbo.YourTable
SELECT CREATEDATE FROM
(
SELECT
(CASE WHEN (ISDATE(#data) > 0) THEN CONVERT(DATE, CREATEDATE)
ELSE CONVERT(DATE, '01/01/1900') END) as CREATEDATE
FROM
[dbo].[TestTB]
) AS Temp
WHERE
CREATEDATE <> CONVERT(DATE, '01/01/1900')
DECLARE #data nvarchar(50)
SET #data = ' 10/9/2014 '
SELECT CONVERT(datetime, #data, 101)
SELECT CONVERT(datetime, CREATEDATE, 101) as CREATEDATE
FROM [dbo].[TestTB]
http://www.sqlfiddle.com/#!6/f2103
please check this http://msdn.microsoft.com/en-us/library/aa226054%28SQL.80%29.aspx
Try this out:
SELECT IIF(ISDATE(CREATEDATE) = 1, CONVERT(DATETIME, CREATEDATE, 110), CREATEDATE) as DT_CreateDate
FROM [dbo].[TestTB]
SQL Fiddle Solution
nvarchar to datetime is an implicit conversion, it means you can do this:
declare #strDate nvarchar(50), #myDate datetime
set #strDate = '01/26/2013'
set #myDate = #strDate
But your problem is date format so you have to convert it, but you have to scpecify the format or style and the code of the style you're using is 101 (according to this table) so the secure way:
declare #strDate nvarchar(50), #myDate datetime
set #strDate = '01/26/2013'
set #myDate = CONVERT(DATETIME, #strDate, 101)
You can skip the code but with diferent configuration(server) that code will break.
If you use the ISO style (yyyymmdd) you never would'nt have to worry and the conversion would be implicit:
declare #strDate nvarchar(50), #myDate datetime
set #strDate = '20150421' --ISO style (yyyymmdd)
set #myDate = #strDate

SQL Custom datetime format to datetime

I have a varchar which is coming through as the following format: yyyy-dd-MM hh:mm:ss
I need to be able to convert that to a valid datetime, what will be the best method?
Edit for example:
DECLARE #d varchar = '2014-17-01 12:00:00'
SELECT CONVERT(DATETIME, #d, 103);
returns
Msg 241, Level 16, State 1, Line 3
Conversion failed when converting date and/or time from character string.
Via CONVERT?
SELECT CONVERT(DATETIME, '2014-31-01 17:00:00', 103 /* British */);
(No column name)
2014-01-31 17:00:00.000
You can use CONVERT as:
DECLARE #TodayDate datetime
SET #TodayDate = GETDATE()
SELECT CONVERT(VARCHAR, #TodayDate, 110) AS TodayDate
Output:
07-04-2014
Hope it helps !
EDITED to add SET DATEFORMAT. This resolved the error for me and ensures everything gets into the correct bucket.
SET DATEFORMAT ydm
DECLARE #d VARCHAR(20) = '2014-17-01 12:00:00';
DECLARE #targetDate DATETIME = GETDATE(); -- Control Date
DECLARE #passedDate DATETIME = CAST(#d AS DATETIME);
SELECT #targetDate, #passedDate;
Try to interchange day and month and then PARSE new string to datetime.
DECLARE #d varchar(50) = '2014-17-01 12:00:00'
DECLARE #year varchar(10) = SUBSTRING(#d,1,4)
DECLARE #day varchar(10) = SUBSTRING(#d,6,2)
DECLARE #month varchar(10) = SUBSTRING(#d,9,2)
DECLARE #time varchar(10) = SUBSTRING(#d,12,8)
DECLARE #new_d varchar(50) = #year+'-'+#month+'-'+#day+' '+#time
SELECT PARSE(#new_d AS datetime USING 'en-US') as Result

SQL Server Optional Parameter Date from to

I have a stored procedure and I want to search between the from and to date, but:
if #FromDate is not null and #ToDate is not null then
vSaleDetail.date between #FromDate and #ToDate
if #FromDate is not null and #ToDate is null then
vSaleDetail.date = #FromDate
if #FromDate is null and #ToDate is then
Return All
This is what I have but it is not working
where
(((#FromDate is null and #ToDate is null) OR (vSaleDetail.date between #FromDate and #ToDate ))
AND ((#FromDate is null) OR (vSaleDetail.date = #FromDate)))
Please help — what do I need to do to fix it?
I would poulate the null parameters with dates way outside the range you need. So If form date is null, I would populate with the earlies t accepatable date in your database's datetime data type. The To date would be poulated with the latest possible date. Then you don't need to use all that complex logic which slows things down.
IF #FromDate is null
Begin
Set #Fromdate = '17530101'
END
IF #ToDATE is null
BEGIN
SET #Todate = '99991231'
END
select ...
WHERE vSaleDetail.date >=#FromDate and <= #ToDate
You can try this:
WHERE (vSaleDetail.date BETWEEN #FromDate AND ISNULL(#ToDate,#FromDate)
OR COALESCE(#FromDate, #ToDate) IS NULL)
ISNULL(p1, p2):
if p1 IS NULL then p2 is returned, otherwise p1 is returned
COALESCE(p1, p2, ...):
Like ISNULL(). returns p1 unless it is NULL, in which case, p2 is returned unless it is NULL, in which case p3.... if all parameters in COALESCE() are null, NULL is returned.
Try this:
WHERE
(
( #FromDate IS NULL AND #ToDate IS NULL)
OR
( vSaleDetail.date BETWEEN #FromDate AND #ToDate )
)
OR <-- #FromDate IS NULL AND #FromDate IS NULL
( #FromDate IS NULL OR vSaleDetail.date = #FromDate )
declare #default_min_date datetime;
declare #default_max_date datetime;
SET #default_min_date = 0
SET #default_max_date = 2958463;
SELECT *
FROM MyTable
WHERE
myDateColumn >= Isnull(#DateFrom, #default_min_date) AND myDateColumn <= Isnull(#DateTo, #default_max_date)
AND (#DateFrom IS NULL OR CONVERT(DATETIME, [CreationDate], 103) BETWEEN CONVERT(DATETIME, #DateFrom, 103) AND DATEADD(DAY, 1, CONVERT(DATETIME, ISNULL(#DateTo, #DateFrom), 103)))

SQL convert DATETIME TO VARCHAR?

I am working on a query something require DATE!!
DECLARE #YesterDay DATETIME, #Today DATETIME
SET #YesterDay = DateAdd(DD, DateDiff(DD, 0, GETDATE())-1, 0)
SET #Today = DateAdd(DD, DateDiff(DD, 0, GETDATE()), 0)
select #YesterDay = convert(varchar, getdate()-1 , 110)
select #Today = convert(varchar, getdate() , 110)
EXEC #return_value = [dbo].[post_sec_admin_list_user_log]
#pDateFr = #YesterDay ,
#pDateTo = #Today,
#pName = '',
#pSec = NULL
#DateFr is varchar(50)
#DateT0 is varchar(50)
the #dateFr and #dateTo are both varchar..
And I try to execute it, it print the time format as this 2011-06-09 16:15:38.927
error statement
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Additionally, the varchar format I need is MM-DD-YYYY
Anyone know where is my error at?
thanks
Your code is confusing:
DECLARE #YesterDay DATETIME, #Today DATETIME
SET #YesterDay = DateAdd(DD, DateDiff(DD, 0, GETDATE())-1, 0)
SET #Today = DateAdd(DD, DateDiff(DD, 0, GETDATE()), 0)
select #YesterDay = convert(varchar, getdate()-1 , 110)
select #Today = convert(varchar, getdate() , 110)
So you declare it as DATETIME, set value with DateDiff then overwrite that value with an varchar representation of a date that is recalculated using different method.
At line 4 and 5 #Yesterday and #Today variables are still DATETIME, because it's declared that way.
EDIT: As mentioned in the comment to my answer you need a variable to pass to the procedure.
So the correct fix would be to declare the variables as VARCHAR(50) at the beginning and do the conversion directly.
DECLARE #YesterDay VARCHAR(50), #Today VARCHAR(50)
SELECT #YesterDay = convert(varchar(50), dateadd(dd, -1, getdate()) , 110)
SELECT #Today = convert(varchar(50), getdate() , 110)
And then call the procedure the way you did originally.
My guess is that getdate()-1 part is wrong.
Also, you were making dateadd and datediff why? Try it like this:
SET #YesterDay = dateadd(dd, -1, GETDATE())
SET #Today = GETDATE()
select #YesterDay = convert(varchar(50), dateadd(dd, -1, getdate()) , 110)
select #Today = convert(varchar(50), getdate() , 110)
EXEC #return_value = [dbo].[post_sec_admin_list_user_log]
#pDateFr = #YesterDay ,
#pDateTo = #Today,
#pName = '',
#pSec = NULL