Converting Date/Time from String Error When Using Cast - sql

I am getting a "Unable to Convert Date/Time from Character String" error message when I run my Access query, but I am not sure why. I have used this method before and have not had any trouble.
SET NOCOUNT ON
DECLARE #StartDate date = '[Start date]', #EndDate date = '[End date]'
SELECT
CAST (Date as Date) as LocalDay
,SalesID
,Status
,Wait
,PO_Number
FROM
cpo_test.dbo.table_agent_detail_view
WHERE Date BETWEEN #StartDate And #EndDate
AND SOURCEID=1
Why is Cast not working in this instance?

The problem is not with the CAST, it's with
DECLARE #StartDate date = '[Start date]', #EndDate date = '[End date]'
I get the same error in SSMS if I try to execute that statement alone. The problem goes away if I change it to
DECLARE #StartDate date = '2018-01-01', #EndDate date = '2018-12-31'
It's not clear what you are trying to accomplish by assigning the string value '[Start date]' to a date variable, but you're going to have to figure out another way to do it.
Note: You call it your "Access query" but it is not Access SQL, it's T-SQL (SQL Server) so I assume that you're running it as a pass-through query in Access. If so, then be aware that pass-through queries behave quite differently from regular Access queries because they are not processed by the Access expression evaluator or the Access Database Engine, they are passed directly to the ODBC data source (hence the name "pass-through query").

I think you are missing a cast in Date near where condition on your query.
Try
SELECT
CAST (Date as Date) as LocalDay
,SalesID
,Status
,Wait
,PO_Number
FROM
cpo_test.dbo.table_agent_detail_view
WHERE CAST (Date as Date) BETWEEN #StartDate And #EndDate
AND SOURCEID=1

Related

How to convert datetime to date without using convert function in sql server

I'm trying to convert datetime to date using convert function. But it is taking large as there is huge data in the table.
Is there any other way to do this without using convert function in less time.
Query:
Select *
from address
where convert(date,record-created_date) between '6/29/2016' and '6/30/2016'
You can simply remove CONVERT function as following query, so no time is spent for converting, but instead you have to add time to your [record-created_date] column in the WHERE clause:
SELECT *
FROM [address]
WHERE [record-created_date] BETWEEN '6/29/2016 00:00:00:000' AND '6/30/2016 23:59:59:999'
With SQL 2008 you can use CAST:
select cast(record-created_date as date)
In older versions, you can use DATEADD/DATEDIFF:
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, record-created_date))
You can define 2 constants in advanced, thus avoid using convert function on the column:
declare #min_date datetime
declare #max_date datetime
set #min_date = convert(datetime, '06/29/2016', 101)
-- Max date needs to be the next date of your end date
set #max_date = convert(datetime, '06/30/2016', 101) + 1
Select *
from address
where record-created_date >= #min_date
and record-created_date < #max_date
Just omit the conversion and add one day to the end date:
where record_created_date between '6/29/2016' and '7/1/2016'
This is interpreted as <= '7/1/2016 0:00', so use this short form only if is okay that midnight of the following day is included. Otherwise use the long form:
where record_created_date >= '6/29/2016' and record_created_date < '7/1/2016'
...or add the time:
where record_created_date between '6/29/2016' and '6/30/2016 23:59:59.999'
Btw., I think it is better to use the date format '2016-06-29' for hardcoded dates.
Anyway the main reason for being slow is most likely a missing index for this column.

T-SQL 2008 Convert Date and time string to datetime

I have two columns in my table, one to capture time and one to capture date. Unfortunately, both are varchar(). I need to take the two fields, concatenate them together, and then convert them to datetime.
I am trying to accomplish that with this:
select CONVERT(datetime,(select txt_returned_date+' '+CONVERT(varchar(20),CONVERT(TIME,txt_time_returned))),126)
from table_name
I am getting this error message:
Conversion failed when converting date and/or time from character string.
The date is being captured as "20130308" as a string. Time is being captures as "4:27 PM" as a string
What I am doing here is converting the string of the time to TIME, then back to varchar. Then I am concatenating them together. This works by itself, but once I introduce the CONVERT(datetime) to the whole query, it is giving me the error.
Any help to try to accomplish this is helpful. Thanks!
You can concatenate the DATE and TIME values together once they have been converted to a DATETIME. Here's a sample to play with that shows concatenating a DATE column and a TIME column that have been stored as VARCHAR:
-- Set up some variables to test with
DECLARE #myTime TIME = GETDATE()
, #myDate DATE = GETDATE()
, #myTimeTxt VARCHAR(16)
, #myDateTxt VARCHAR(10);
-- Initialize your variables
SELECT #myTimeTxt = #myTime
, #myDateTxt = #myDate;
-- Display your separated values
SELECT #myDateTxt, #myTimeTxt;
-- Display your concatenated value
SELECT CAST(#myDateTxt AS DATETIME) + CAST(CAST(#myTimeTxt AS TIME) AS DATETIME);
You can use this option
DECLARE #date date = '20010101',
#time time = '01:01:01'
SELECT CAST(#date AS datetime) + #time
Result:2001-01-01 01:01:01.000
Demo on SQLFiddle
Are you using SQL 2012? If so you may be able to use the datetimedromparts function to achieve this. If not for this specific example, it's always good to know for the future :)
http://technet.microsoft.com/en-gb/library/hh213233.aspx

dateadd - finding a date in the past

I have an odd problem with subtracting 18 months from a date.
Consider the following snippet:
Convert(dateTime,CREATION_DATE,103) >
DateAdd (MONTH, -18, Convert (DateTime, #IN_ACTIVITY_DATE, 103))
This forms part of a where clause in a stored procedure. When I run:
exec theSP #IN_ACTIVITY_DATE = '21/02/2013'
it runs fine, but when I change it to this:
exec theSP #IN_ACTIVITY_DATE = '21/01/2013'
it breaks with the error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Does anyone have any thoughts on why it might be January (all other months are ok) that is breaking my code?
Thanks.
DS
To pass string as datetime use ISO format as yyyymmdd which guaranteed to work in any server with any culture info.;
exec theSP #IN_ACTIVITY_DATE = '20130121'
Also as a side note, if CREATION_DATE is already datetime then you don't need to CONVERT CREATION_DATE for comparison.
--if CREATION_DATE is DATETIME/DATE column
CREATION_DATE >
DateAdd (MONTH, -18, Convert (DateTime, #IN_ACTIVITY_DATE))
Specify the date in YYYY-MM-DD format.
Eg.:
exec theSP #IN_ACTIVITY_DATE = '2013-01-21'
Also, you can use SET DATEFORMAT to specify the date format:
Eg.:
SET DATEFORMAT dmy;
exec theSP #IN_ACTIVITY_DATE = '21/02/2013'
exec theSP #IN_ACTIVITY_DATE = '21/01/2013'
SET DATEFORMAT: Sets the order of the month, day, and year date parts for interpreting date, smalldatetime, datetime, datetime2 and datetimeoffset character strings.
SET DATEFORMAT { format | #format_var }
format | #format_var: Is the order of the date parts. Valid parameters are mdy, dmy, ymd, ydm, myd, and dym.
There might be something in your database, perhaps a check constraint, that doesn't like the January date. The conversion to seems to work on SQL Server 2008 (Fiddle). Something else might be causing the problem.
Also, the date formatting suggestions provided by the others are good advice.

SQL - Date Query Issue - varchar to datetime conversion resulted in out-of-range value

I have a SQL query written by a colleague who is no longer here. The query runs as part of an SSIS job, and as of this month has started failing with the following error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The query itself is just a basic select with a where clause that looks for values in a certain time range (the date range between #startdate and #enddate)
The code to determine the time range is below:
DECLARE #RunDateTime datetime
DECLARE #RunDate datetime
DECLARE #StartDate datetime
DECLARE #EndDate datetime
DECLARE #Month int
DECLARE #Year int
DECLARE #strStartDate varchar(10)
SET #RunDateTime = GetDate()
SET #RunDate = cast(round(convert(real, #RunDateTime),0,1) as datetime)
IF DATEPART(d, #RunDate) = 16
BEGIN
SET #StartDate = DATEADD(d, -15, #RunDate)
SET #EndDate = #RunDate
END
ELSE
BEGIN
IF Month(#RunDate) = 1
SET #Month = 12
ELSE
SET #Month = Month(#RunDate) - 1
IF Month(#RunDate) = 1
SET #Year = Year(#RunDate) - 1
ELSE
SET #Year = Year(#RunDate)
SET #strStartDate = CONVERT(varchar(2), #Month)+ '/16/' + CONVERT(varchar(4), #Year)
SET #StartDate = CONVERT(datetime, #strStartDate, 101)
SET #EndDate = #RunDate
END
This job runs twice a month. Once on the 16th for data from the 1st to the 15th of the month, and once on the 1st of the next month for data from the 16th to the end of the previous month.
From what I can find online, the use of the varchar for strStartDate is the likely culprit? I'm not familiar enough with SQL to know how to replace all that convert stuff that's going on there? Also, is there a better way to determine the end of the month date than just getting the run time? Any help at all would be greatly appreciated.
(PS, we run this job on SQL Server 2008 R2) And I checked with the DBA and he said nothing about localization or regional settings has changed on the SQL server.
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependant 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.
Also: with SQL Server 2008, it is recommended to use DATETIME2 (instead of DATETIME) if at all ever possible. DATETIME2 parsing of strings is a lot more forgiving for error and/or different formats (like US AM/PM formatting etc.) .
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.

How to filter only the date from a string stored in a varchar

Ii have values stored in the SQL Server in the following manner : 02-Jul-12 12:00:00 AM here the time and minutes, seconds can be anything like 02-Jul-12 12:15:52 PM ,02-Jul-12 6:02:12 AM so on.
I want to have a where condition which will omit the time and take the data based on the date like the following where some_Date='02-Jul-12'
How would I do this?
SELECT * FROM whatever WHERE some_Date LIKE '02-Jul-12%';
If you are on SQL2008 or later, you can cast your DATETIME to DATE.
See this post: http://blog.sqlauthority.com/2012/09/12/sql-server-get-date-and-time-from-current-datetime-sql-in-sixty-seconds-025-video/
But in a WHERE-clause it is better to search between dates, like this:
DECLARE #startDate DATETIME = '02-Jul-2012'
DECLARE #endDate DATETIME = DATEADD(DAY, 1, #startDate)
SELECT * FROM [table] WHERE [some_Date] BETWEEN #startDate AND #endDate
SELECT * FROM dbo.tbl_MyTable
WHERE
REPLACE(CONVERT(VARCHAR(9), DateTimeValueColumn, 6), ' ', '-')='02-Jul-12'
or
On chage in code is instead of using getdate function voncert you datestring in datetime format and do compare this follow query will work for you
SELECT * FROM dbo.tbl_MyTable
WHERE
CAST(CONVERT(CHAR(10), DateTimeValueColumn, 102) AS DATE) =
CAST(CONVERT(CHAR(10),GETDATE(),102) AS DATE)
If you are storing dates as characters -- which is not recommended -- you should at least use ISO format: YYYY-MM-DD hh:mm:ss. This makes the date useful for sorting and comparisons ("<" works, ">" works, "between" works as well as equals).
To extract the date, you can then use left(datestr, 10). In your format, you would use:
where left(datestr, 9) = '01-Jan-13'
If you are storing the fields as a datetime or smalldatetime, you may think they are stored as a string. They are not. They are stored as some number of days since some particular date, with day parts stored as fractional days. If you are using SQL Server 2005 or greater, then the best way is:
where cast(datetime as date) = '2013-01-01' -- I recommend ISO formats, even for constants. '20130101' is even better
To select rows with today's date (not time)
select * from myTable where datediff(dd, dateColumn, getdate()) = 0