x

convert datetime error

Hi I have a stored procedure that is trying to pass datetime parameters @StartDate and @EndDate but when I run the query I get the following Error....

Arithmetic overflow error converting expression to data type datetime.

Below is my Stored Procedure....

ALTER Procedure [dbo].[Test]  
 @StartDate  datetime, @EndDate  datetime
as 

begin
set nocount on;

-- exec test '01/01/2009','01/01/2020'

SELECT DISTINCT
  F.EpisodeSys ,
   F.ResidentSys ,
  VR.DisplayName ,
  F.OrgEntSys AS FacilityID ,
  VO.FacilityName ,
  VE.AdmissionDate ,
  VE.DischargeDate
  FROM     [D].dbo.FactLoadExceptions AS F
  INNER JOIN [B].dbo.VisionvwResidents AS VR
  ON F.ResidentSys = VR.EntitySys
  INNER JOIN [B].dbo.VisionvwOrganizations AS VO
  ON F.OrgEntSys = VO.OrgEntSys
  INNER JOIN [B].dbo.VisionEpisodes AS VE
  ON F.EpisodeSys = VE.EpisodeSys
  WHERE    CensusDateKey >= @StartDate
  AND CensusDateKey <= @EndDate
  ORDER BY AdmissionDate
end
I should note that The CENSUSDATEKEY field is an INT type I need to convert it to Datetime type
more ▼

asked Oct 11 '12 at 07:09 PM in Default

tombiernacki gravatar image

tombiernacki
338 18 20 23

So what values are in the CensusDateKey field?
Oct 11 '12 at 08:06 PM ThomasRushton ♦
The CensusDateKey has int date values like 20090101
Oct 11 '12 at 08:09 PM tombiernacki
(comments are locked)
10|1200 characters needed characters left

2 answers: sort voted first

... CAST(CAST(CensusDateKey AS CHAR(8)) AS DATETIME) >= @StartDate AND CAST(CAST(CensusDateKey AS CHAR(8)) AS DATETIME) <= @EndDate ...

should fix it.
more ▼

answered Oct 12 '12 at 06:16 AM

eghetto gravatar image

eghetto
2.1k 15 17 21

Awesome that worked perfectly
Oct 12 '12 at 03:39 PM tombiernacki
(comments are locked)
10|1200 characters needed characters left

You need to be sure that there is valid data in the CensusDateKey column. One way of doing it is to execute a query using ISDATE function, something like

SELECT CensusDateKey FROM TABLENAME
WHERE ISDATE(CONVERT(VARCHAR,CensusDateKey)) = 0
This will give you any invalid data. Not to mention, storing date data in other data types always gives pain.
more ▼

answered Oct 12 '12 at 07:47 AM

Usman Butt gravatar image

Usman Butt
13.9k 6 8 14

(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x401
x91

asked: Oct 11 '12 at 07:09 PM

Seen: 817 times

Last Updated: Oct 13 '12 at 06:42 PM