Here’s a UDF function for SQL 2000 that will save you datetime headaches when passing datetime variables into your SQL Procedures. The function converts any datetime field to ensure that you don’t lose data for the last day to be included.

Some SQL Procedures use ‘between’ when quering datetime fields. This may cause you to lose data on the last day:

In the following statement: ‘Select * from labor where employee = ‘1’ and transaction_date between ’07/09/01′ and ’07/12/01′
If you dont change ’07/12/01′ to ’07/12/01 23:59:59′ it will not include all of 7/12

A solution is to rewrite the SQL to ‘Select * from table where transaction_date >= ‘20010709’ and transaction_date

This function converts any datetime field to this format for your queries that use datetime datatypes.

One Use Example:

Declare @FromDate datetime,
@ToDate datetime
Set @FromDate = Dateadd(d,-7,getdate()
Set @ToDate = getdate()
select * from table where transaction_date >=
dbo.fn_simpleDT(@FromDate,1) AND transaction_date
<= dbo.fn_simpleDT(@ToDate,1) fn_simpledate(datetime field, format ) Format = 1 is 'yyyymmdd' Format <> 1 is ‘yyyyddmm’

Author: Anthony Loera

Download Script:

We hope that the information on these script pages is
valuable to you. Your use of the information contained in these pages,
however, is at your sole risk. All information on these pages is provided
“as -is”, without any warranty, whether express or implied, of its accuracy,
completeness, or fitness for a particular purpose…

Disclaimer Continued

Back to Database Journal Home

Get the Free Newsletter!

Subscribe to Cloud Insider for top news, trends & analysis

Latest Articles