Showing posts with label datetime. Show all posts
Showing posts with label datetime. Show all posts

Tuesday, March 27, 2012

DAYS 360 Function

Hi,

Does anyone has the DAYS360 excel formula in a function in sqlserver ? I did this one

FUNCTION dbo.fnDays360_EXCEL
(
@.startDate DateTime,
@.endDate DateTime
)
RETURNS int
AS
BEGIN
RETURN (
(CASE
WHEN Day(@.endDate)=31 THEN 30
ELSE Day(@.endDate)
END) -
(CASE
WHEN Day(@.startDate)=31 THEN 30
ELSE Day(@.startDate)
END)
+ ((DatePart(m, @.endDate) + (DatePart(yyyy, @.endDate) * 12))
-(DatePart(m, @.startDate) + (DatePart(yyyy, @.startDate) * 12))) * 30)
END

But there is a bug, if the end date is bigger then february, february must have 30 days and not 28 or 29...

Does anyone has the solution ?

Thanks

Hi,

Do you mean 30/360? HEre's some C# code that was tested thouroughly, you should be able to get the idea. If you meant Act/360 get back to me.

Good luck,

John

double YearFrac(DateTime dtStartDate, DateTime dtEndDate, int iDaycount)

{

/* According to Excel:

Basis Day count basis

0 or omitted US (NASD) 30/360

1 Actual/actual

2 Actual/360

3 Actual/365

4 European 30/360

7 Bus/252

*/

switch( iDaycount )

{

case 0: // 30/360 (ISDA)

{

int d1, m1, y1, d2, m2, y2;

d1 = dtStartDate.Day;

m1 = dtStartDate.Month;

y1 = dtStartDate.Year;

d2 = dtEndDate.Day;

m2 = dtEndDate.Month;

y2 = dtEndDate.Year;

// ISDA rules

if (d1 == 31) d1 = 30;

if (d2 == 31 && d1 == 30) d2 = 30;

return (360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1)) / 360e0;

}

|||

Use the following code...

Code Snippet

Create Function dbo.Days360

(

@.StartDate Datetime,

@.EndDate Datetime

)

Returns Int

as

Begin

Declare

@.d1 int, @.d2 int,

@.m1 int, @.m2 int,

@.y1 int, @.y2 int;

Select @.d1 = Day(@.StartDate), @.m1 = Month(@.StartDate), @.y1 = Year(@.StartDate),

@.d2 = Day(@.EndDate), @.m2 = Month(@.EndDate), @.y2 = Year(@.EndDate)

If (day(@.StartDate) = 1) And (month(@.StartDate) = 3)

Select @.d1 = 30

If (@.d2 = 31) And (@.d1 = 30)-- Then

Select @.d2 = 30

Return ((@.y2 - @.Y1) * 360) + ((@.m2 - @.m1) * 30) + (@.d2 - @.d1)

End

go

Select dbo.Days360('1/20/2007', '2/3/2007')

|||

Hi,

There is a problem to this case Select dbo.Days360('1/31/2007', '4/15/2007') it returns 74 instead of 75

Thanks

|||

Hi

There is a problem to this case Select dbo.Days360('1/31/2007', '4/15/2007') it returns 74 instead of 75

And for this one also..

Select dbo.Days360('2/28/2007', '3/31/2007') that must return 30

For the C# code...is just this last error

Sunday, March 25, 2012

Daylight savings

Anyone if SQL server has any built-in mechanism for handling Daylight savings?
Mostly for figuring out time passed between two datetime values...
Thanks in advance.Anyone if SQL server has any built-in mechanism for handling Daylight savings?

No, since it's a regional thing anyway

Mostly for figuring out time passed between two datetime values...

Yes...DATEDIFF

What are you trying to do?|||well, like you said I use DATEDIFF to get the amount of time passed between two dates...but (where I live daylight time shifts backwards at 2 (to 1 am) am last sunday of october, and forward at 2 am (to 3 am) on first sunday of april.

basically I want to count time properly...

DATEDIFF(Minute, '2004-04-04 1:30', '2004-04-04 3:30') gives 120 but in reality only 60 minutes passed between the first and second time.|||well, like you said I use DATEDIFF to get the amount of time passed between two dates...but (where I live daylight time shifts backwards at 2 (to 1 am) am last sunday of october, and forward at 2 am (to 3 am) on first sunday of april.

basically I want to count time properly...

DATEDIFF(Minute, '2004-04-04 1:30', '2004-04-04 3:30') gives 120 but in reality only 60 minutes passed between the first and second time.|||You need to build a table that holds (perhaps by region) the dates and times that the switch occurs.

There are some places in the states (by county level even) where the switch does not occur.

Anyway. If the dates EXISTS in the range, then you need to handle it accordingly.

Most likely with a CASE Statement|||If both of the DATETIME values are from the same locale as the server, you could use the GetUTCDate() (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_ga-gz_4kkp.asp) to convert them both to UTC, then take the DateDiff() of the UTC DATETIME values. If the DATETIME values are from different locales, let me know how you do it!

-PatP|||It say GetUTCDate() Requires 0 parameters...|||GetUTCDate() works just like GetDate(), but expresses the date/time returned as UTC (also known as Greenwich or Z time) instead of local time. If your app stores server based times in UTC (which is effectively mandated if you have servers in more than one timezone), then life is simple. If you have times stored based on local time, then things get to be really interesting!

Oh yeah, I forgot to mention, there isn't any way to dependably convert a stored local time to Z time, although you can convert Z time to local time if you know which local time.

-PatP

Day of year

How would I get the day of year from a datetime field in a query?
Such as Feb. 28 would be day 59.
Thank youSELECT DATEPART(DAYOFYEAR,'20050228') ;
David Portas
SQL Server MVP
--
"Lyners" <Lyners@.discussions.microsoft.com> wrote in message
news:78DFFDDD-9227-4A95-896E-F50FDCBB4E17@.microsoft.com...
> How would I get the day of year from a datetime field in a query?
> Such as Feb. 28 would be day 59.
> Thank you

Day of the week

Hi group ,
Please let me know which formule is usefull for calculate the day of week
based in a date.
my date is datetime.
day = convert(int,MyDate) % 7
is't working
Look up DATENAME & DATEPART functions in SQL Server Books Online.
Anith
|||SELECT DATENAME(dw, getdate())
|||But I need the number of the week. thanks you anyway.
Best regard
MArio
"Julie" <anonymous@.discussions.microsoft.com> wrote in message
news:BBA8C3BE-0086-49B4-B109-843FEEBED93D@.microsoft.com...
> SELECT DATENAME(dw, getdate())
|||? number of the week, or day of the week? Your message and subject don't
agree.
In any case, as Anith suggested, look at DATENAME and DATEPART in Books
Online.
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/
"Mario Reiley" <mreiley@.cantv.net> wrote in message
news:#gi0eLENEHA.2640@.TK2MSFTNGP12.phx.gbl...
> But I need the number of the week. thanks you anyway.
|||I like this formula:
(@.@.DATEFIRST + DATEPART(dw, date) ) % 7
It is always
0 on Sunday
1 on Monday
2 on Monday
up to
6 on Friday

Day of the week

Hi group ,
Please let me know which formule is usefull for calculate the day of week
based in a date.
my date is datetime.
day = convert(int,MyDate) % 7
is't workingLook up DATENAME & DATEPART functions in SQL Server Books Online.
--
Anith|||But I need the number of the week. thanks you anyway.
Best regard
MArio
"Julie" <anonymous@.discussions.microsoft.com> wrote in message
news:BBA8C3BE-0086-49B4-B109-843FEEBED93D@.microsoft.com...
> SELECT DATENAME(dw, getdate())|||? number of the week, or day of the week? Your message and subject don't
agree.
In any case, as Anith suggested, look at DATENAME and DATEPART in Books
Online.
--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/
"Mario Reiley" <mreiley@.cantv.net> wrote in message
news:#gi0eLENEHA.2640@.TK2MSFTNGP12.phx.gbl...
> But I need the number of the week. thanks you anyway.sql

Day of the week

Hi group ,
Please let me know which formule is usefull for calculate the day of week
based in a date.
my date is datetime.
day = convert(int,MyDate) % 7
is't workingLook up DATENAME & DATEPART functions in SQL Server Books Online.
Anith|||SELECT DATENAME(dw, getdate())|||But I need the number of the week. thanks you anyway.
Best regard
MArio
"Julie" <anonymous@.discussions.microsoft.com> wrote in message
news:BBA8C3BE-0086-49B4-B109-843FEEBED93D@.microsoft.com...
> SELECT DATENAME(dw, getdate())|||? number of the week, or day of the week? Your message and subject don't
agree.
In any case, as Anith suggested, look at DATENAME and DATEPART in Books
Online.
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/
"Mario Reiley" <mreiley@.cantv.net> wrote in message
news:#gi0eLENEHA.2640@.TK2MSFTNGP12.phx.gbl...
> But I need the number of the week. thanks you anyway.|||I like this formula:
(@.@.DATEFIRST + DATEPART(dw, date) ) % 7
It is always
0 on Sunday
1 on Monday
2 on Monday
up to
6 on Friday

Thursday, March 22, 2012

Datetime/public holidays

I need to be able to determine whether a particular
datetime value is a public holiday (in the uk) or not and
I cannot find a documented way of deteriming this. Please
could you advise me whether there is a function or method
of determining this in SQL 2000 Enterprise Edition?
If there is not could you advise me a robust method of
providing this functionality for developers (I am a design
DBA who works with a number of different development teams
and it would seem appropriate for everyone to use the same
method)?
Many thanks,
DavePublic holiday dates are not always determined by a fixed logic. You should
build your own calendar table for this and populate it in advance with as
much data as you need.
CREATE TABLE Calendar (caldate DATETIME NOT NULL PRIMARY KEY, workingday
CHAR(1) NOT NULL CHECK (workingday IN ('Y','N')) DEFAULT 'Y')
INSERT INTO Calendar (caldate) VALUES ('20000101')
Populate it (this is 11 years worth of dates):
WHILE (SELECT MAX(caldate) FROM Calendar)<'20101231'
INSERT INTO Calendar (caldate)
SELECT DATEADD(D,DATEDIFF(D,'19991231',caldate),
(SELECT MAX(caldate) FROM Calendar))
FROM Calendar
Now update the non-working days:
UPDATE Calendar SET workingday = 'N'
WHERE DATENAME(DW,caldate) IN ('Saturday','Sunday')
A source I use for public holiday dates is: http://www.bank-holidays.com
--
David Portas
--
Please reply only to the newsgroup
--

DateTime.Min won't insert into SQL Server Mobile 3.0

Hi all,

In my C# code I have a Class property that takes the value DateTime.Min upon initialisation, but when I try to insert this into the database column (yes, it is DateTime data type :)) I get an 'Unexpected Error' from SQL Server Mobile.

Is this a known?

Tryst

Hi

It is due to the diffrence between the Min date of C# and the Min Date of SQL Server. The Min Date in C# is 01/01/01 while in SQL Server it is 01/01/1753 ... so create your own Min Date equlient to SQL Server Min Date and the Problem will be resolved.

|||ok, thanks, Akbar Khan.sql

DATETIME, DATEPART, CONVERT and Time Zones

Hi,
all my research seems to indicate that there is no correct way to get
DATEPART and CONVERT to honor time zones other than the one of the server.
Ideally I'd like to do something like
SELECT DATEPART( hh, GETDATE(), 'Europe/Berlin' )
SELECT DATEPART( hh, GETDATE(), 'PST' )
The only solution seems to be to write a user defined function that does
this; however this is tedious, inefficient and likely causes a maintenance
nightmare. Client side processing is not an option as this prevents
proper usage of GROUP BY by the database. (see [1])
Any other options that I overlooked?
Kind regards
robert
[1]
http://groups.google.com/group/micr...23dc8e8594af322Robert,
Perhaps this may help?
See:
GETUTCDATE()
http://msdn.microsoft.com/library/d...br />
4kkp.asp
HTH
Jerry
"Robert Klemme" <bob.news@.gmx.net> wrote in message
news:Ozplp1K2FHA.164@.TK2MSFTNGP10.phx.gbl...
> Hi,
> all my research seems to indicate that there is no correct way to get
> DATEPART and CONVERT to honor time zones other than the one of the server.
> Ideally I'd like to do something like
> SELECT DATEPART( hh, GETDATE(), 'Europe/Berlin' )
> SELECT DATEPART( hh, GETDATE(), 'PST' )
> The only solution seems to be to write a user defined function that does
> this; however this is tedious, inefficient and likely causes a maintenance
> nightmare. Client side processing is not an option as this prevents
> proper usage of GROUP BY by the database. (see [1])
> Any other options that I overlooked?
> Kind regards
> robert
>
> [1]
> http://groups.google.com/group/micr...23dc8e8594af322
>|||Robert,
And possibly this as well:
Why should I consider using an auxiliary calender table?
http://www.aspfaq.com/show.asp?id=2519
HTH
Jerry
"Robert Klemme" <bob.news@.gmx.net> wrote in message
news:Ozplp1K2FHA.164@.TK2MSFTNGP10.phx.gbl...
> Hi,
> all my research seems to indicate that there is no correct way to get
> DATEPART and CONVERT to honor time zones other than the one of the server.
> Ideally I'd like to do something like
> SELECT DATEPART( hh, GETDATE(), 'Europe/Berlin' )
> SELECT DATEPART( hh, GETDATE(), 'PST' )
> The only solution seems to be to write a user defined function that does
> this; however this is tedious, inefficient and likely causes a maintenance
> nightmare. Client side processing is not an option as this prevents
> proper usage of GROUP BY by the database. (see [1])
> Any other options that I overlooked?
> Kind regards
> robert
>
> [1]
> http://groups.google.com/group/micr...23dc8e8594af322
>|||Jerry Spivey <jspivey@.vestas-awt.com> wrote:
> Robert,
> Perhaps this may help?
> See:
> GETUTCDATE()
> http://msdn.microsoft.com/library/d...kkp.a
sp
I know that but I can't see how this may help. Note that we need to be able
to to queries that GROUP BY such a datepart table, e.g.
SELECT DATEPART( hh, GETDATE(), 'Europe/Berlin' ) as [hour], SUM(bytes) as
[volume]
FROM T
GROUP BY DATEPART( hh, GETDATE(), 'Europe/Berlin' )
(simplified)
Kind regards
robert
> HTH
> Jerry
> "Robert Klemme" <bob.news@.gmx.net> wrote in message
> news:Ozplp1K2FHA.164@.TK2MSFTNGP10.phx.gbl...|||Jerry Spivey <jspivey@.vestas-awt.com> wrote:
> Robert,
> And possibly this as well:
> Why should I consider using an auxiliary calender table?
> http://www.aspfaq.com/show.asp?id=2519
That looks better. However, given the complexity introduced by these
factors I think this is not a viable solution:
- larger number of timezones
- wide range of dates
- constant insertions and deletions (records with old timestamps are
removed, new ones are added)
We would constantly need to update the calendar table and do that in a wide
number of time zones. This isn't really going to be effective... But I'll
consider a bit more. Thanks for that pointer!
Kind regards
robert|||Robert,
Would setting up a table of known timezones and adding them to the UTC date
work? A case statement in a user defined function might work as well or
better.
OffsetTable
Name varchar
offset int
name = Europe/Berlin
int 2 -- no clue if correct
name PST
int -12 -- again no clue
DECLARE @.Offset
SELECT @.Offset=offset from OffsetTable WHERE name = 'PST'
SELECT DATEPART( hh, DATEADD(hh, @.Offset, GETUTCDATE())
Regards,
John
"Robert Klemme" <bob.news@.gmx.net> wrote in message
news:Ozplp1K2FHA.164@.TK2MSFTNGP10.phx.gbl...
> Hi,
> all my research seems to indicate that there is no correct way to get
> DATEPART and CONVERT to honor time zones other than the one of the server.
> Ideally I'd like to do something like
> SELECT DATEPART( hh, GETDATE(), 'Europe/Berlin' )
> SELECT DATEPART( hh, GETDATE(), 'PST' )
> The only solution seems to be to write a user defined function that does
> this; however this is tedious, inefficient and likely causes a maintenance
> nightmare. Client side processing is not an option as this prevents
> proper usage of GROUP BY by the database. (see [1])
> Any other options that I overlooked?
> Kind regards
> robert
>
> [1]
> http://groups.google.com/group/micr...23dc8e8594af322
>|||John J. Hughes II wrote:
> Robert,
> Would setting up a table of known timezones and adding them to the
> UTC date work?
I'm afraid no because there is DST. The calculation has to be much more
complex. First you need to determine whether a given point in time is in
DST and then add the corresponding offset. Also, since SQL Server always
uses the TZ of the server it's running on the result may be distorted
again by that TZ's DST...
Thanks anyway!
Kind regards
robert
> A case statement in a user defined function might
> work as well or better.
> OffsetTable
> Name varchar
> offset int
> name = Europe/Berlin
> int 2 -- no clue if correct
> name PST
> int -12 -- again no clue
> DECLARE @.Offset
> SELECT @.Offset=offset from OffsetTable WHERE name = 'PST'
> SELECT DATEPART( hh, DATEADD(hh, @.Offset, GETUTCDATE())
> Regards,
> John
> "Robert Klemme" <bob.news@.gmx.net> wrote in message
> news:Ozplp1K2FHA.164@.TK2MSFTNGP10.phx.gbl...
http://groups.google.com/group/micr...23dc8e8594af322|||On Mon, 24 Oct 2005 17:12:51 +0200, Robert Klemme wrote:

>Hi,
>all my research seems to indicate that there is no correct way to get
>DATEPART and CONVERT to honor time zones other than the one of the server.
>Ideally I'd like to do something like
>SELECT DATEPART( hh, GETDATE(), 'Europe/Berlin' )
>SELECT DATEPART( hh, GETDATE(), 'PST' )
>The only solution seems to be to write a user defined function that does
>this; however this is tedious, inefficient and likely causes a maintenance
>nightmare. Client side processing is not an option as this prevents
>proper usage of GROUP BY by the database. (see [1])
>Any other options that I overlooked?
Hi Robert,
My recommendations for this would be:
1. If you're times are entered in different time zones, then the only
way to get any meaningful information in the database is to transform
them into one time zone BEFORE even storing them in a table. Using UTC
seems the most logical choice. Converting at the client is probably the
best bet, since the client knows in which part of the world it sits.
2. To get the results in different time zones, including correct
handling of DST, set up a table that holds time offsets for all relevant
time zones, and for all periods of DST/non-DST. For example:
CREATE TABLE TimeZoneOffsets
(TimeZone char(4) NOT NULL,
StartDate datetime NOT NULL,
EndDate datetime NOT NULL,
Offset smallint NOT NULL,
PRIMARY KEY (TimeZone, StartDate),
UNIQUE (TimeZone, EndDate),
CHECK (StartDate < EndDate)
)
Store the offset in minutes, to cater for the time zones that are x.5
hours before or after UTC. Make sure that the StartDate and EndDate are
specified in the corrsponding UTC code. Also, make sure that the EndDate
is exactly equal to the StartDate of the next defined period.
When reporting, include an
INNER JOIN TimeZoneOffsets
ON TimeZone = <<RequestedTimeZone>>
AND StartDate >= <<UTC Datetime to be reported>>
AND EndDate < <<UTC Datetime to be reported>>
To find the actual datetime of the event, use
DATEADD(minute, TimeZoneOffsets.Offset, <<UTC datetime>> )
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hugo Kornelis wrote:
> On Mon, 24 Oct 2005 17:12:51 +0200, Robert Klemme wrote:
>
> Hi Robert,
> My recommendations for this would be:
> 1. If you're times are entered in different time zones, then the only
> way to get any meaningful information in the database is to transform
> them into one time zone BEFORE even storing them in a table. Using UTC
> seems the most logical choice. Converting at the client is probably
> the best bet, since the client knows in which part of the world it
> sits.
Yes of course. But this is not the problem we are talking about. The
data is already stored that way.

> 2. To get the results in different time zones, including correct
> handling of DST, set up a table that holds time offsets for all
> relevant time zones, and for all periods of DST/non-DST. For example:
> CREATE TABLE TimeZoneOffsets
> (TimeZone char(4) NOT NULL,
> StartDate datetime NOT NULL,
> EndDate datetime NOT NULL,
> Offset smallint NOT NULL,
> PRIMARY KEY (TimeZone, StartDate),
> UNIQUE (TimeZone, EndDate),
> CHECK (StartDate < EndDate)
> )
> Store the offset in minutes, to cater for the time zones that are x.5
> hours before or after UTC. Make sure that the StartDate and EndDate
> are specified in the corrsponding UTC code. Also, make sure that the
> EndDate is exactly equal to the StartDate of the next defined period.
> When reporting, include an
> INNER JOIN TimeZoneOffsets
> ON TimeZone = <<RequestedTimeZone>>
> AND StartDate >= <<UTC Datetime to be reported>>
> AND EndDate < <<UTC Datetime to be reported>>
> To find the actual datetime of the event, use
> DATEADD(minute, TimeZoneOffsets.Offset, <<UTC datetime>> )
> Best, Hugo
While this looks like a feasible solution it has some drawbacks
- Continuous maintenance of this table is required, as in our case data
with new timestamps is inserted and old data is removed.
- There might not be an easy solution to calculate the data to put into
TimeZoneOffsets. If there was, then it's probably better to put that into
a user defined function.
- Using DATEADD before DATEPART might not yield proper results as
DATEPART still uses only one time zone, the one of the server - and that
might include DST times etc. making this at least more complicated.
- Our product creates queries on the fly. This will have to be made DB
specific (at the moment we still manage to generate uniform SQL) which is
not an issue as such but ATM I don't have the resources at hand.
- This is all quite a bit of effort for something that ought to be part
of the DB. IMHO this is basic functionality (and Oracle has it btw).
Not the silver bullet...
Thanks four your suggestions anyway!
Kind regards
robert|||On Wed, 26 Oct 2005 10:53:48 +0200, Robert Klemme wrote:
(snip)
>While this looks like a feasible solution it has some drawbacks
> - Continuous maintenance of this table is required, as in our case data
>with new timestamps is inserted and old data is removed.
Hi Robert,
If you describe adding two rows per time zone, once every yaer, as
"continuous maintenance", then yes: continuous maintenance is needed. If
you think you'll have to do daily maintenance to the TimeZoneOffsets
table I proposed, then you're misunderstanding what I mean.

> - There might not be an easy solution to calculate the data to put into
>TimeZoneOffsets. If there was, then it's probably better to put that into
>a user defined function.
On the contrary, calculating the data should be easy. For example, in
the Netherlands (where I happen to live), we have DST from March 27 2:00
AM to Oct 30 3:00 AM this year. Our normal time zone is MET, which is
UTC +1. During summer, we are at UTC +2. Here are two of the entries in
TimeZoneOffsets for MET in 2005 and 2006:
Timezone: MET
StartDate: 2005-03-27T01:00:00 -- 2:00 AM MET @. UDT + 1 = 1:00 AM UDT
EndDate: 2005-10-30T01:00:00 -- 3:00 AM MEDT @. UDT + 1 = 1:00 AM UDT
Offset: +120 -- + 2 hours = + 120 minutes
Timezone: MET
StartDate: 2005-10-30T01:00:00 -- 3:00 AM MEDT @. UDT + 1 = 1:00 AM UDT
EndDate: 2005-03-26T01:00:00 -- 2:00 AM MET @. UDT + 1 = 1:00 AM UDT
Offset: +6 -- + 1hour = + 60minutes

> - Using DATEADD before DATEPART might not yield proper results as
>DATEPART still uses only one time zone, the one of the server - and that
>might include DST times etc. making this at least more complicated.
Timezone doesn't affect DATEADD. If I type DATEADD(hour, 24, getdate())
at noon on October 29, the answer will be noon October 30, even though
the end of DST means that it will actually be 11 AM after 24 hours have
passed.
Since the data stored in your database is in UTC and the beginning and
end of DST periods are also specified in UTC, I fail to see how the
result could not be the correct local time. Could you give an example of
how this would produce erroneous results?

> - Our product creates queries on the fly. This will have to be made DB
>specific (at the moment we still manage to generate uniform SQL) which is
>not an issue as such but ATM I don't have the resources at hand.
As far as I know, almost no actual database product supports the ANSI
standard date and time handling functions. All have their own set of
proprietary functions. I don't think that you can generate any uniform
multi-platform SQL that includes date and/or time functions.

> - This is all quite a bit of effort for something that ought to be part
>of the DB. IMHO this is basic functionality (and Oracle has it btw).
If you think standard functionality should be added to SQL Server,
sending mail to sqlwish@.microsoft.com is the way to go. They won't
reply, but they do listen - especially to wishes that are sent in my
many users.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

DateTime without the time

Hi,

Im moving data from a OLE DB Source to a Flat File Destination.


I have a DateTime field in my database.

My current query returns:
2007-05-21 00:00:00

How can I make it return:
2007-05-21

Thank you!! Smile

Use a derived column to cast the field to DT_DBDATE...

(DT_DBDATE)[YourDateTimeField]|||

I′ve modified the query so it returns only the date.

However, the Flat File Destination always changes it back to a DateTime.

|||

MrHat wrote:

I′ve modified the query so it returns only the date.

However, the Flat File Destination always changes it back to a DateTime.

Yes, you need to define the data type of that column to DT_DBDATE in the flat file connection manager.|||My SQL server destination changes back to DT_DBtimestamp.....in my sql table it has datatype of datetime....but I do not want to display the Time.....just the date....any ideas?|||

JStutz wrote:

My SQL server destination changes back to DT_DBtimestamp.....in my sql table it has datatype of datetime....but I do not want to display the Time.....just the date....any ideas?

Displaying just the time is a simple transact-sql statement using the CONVERT function.

|||

Can you use a SQL Command in your source?

If so, use CONVERT(varchar, <dateField>, 112) in your select list

|||

SQL-PRO wrote:

Can you use a SQL Command in your source?

If so, use CONVERT(varchar, <dateField>, 112) in your select list

Still if that's in your source query, you can't store it that way -- not in SQL Server anyway. (Unless you're storing it in a varchar field.)

DateTime without the time

Hi,

Im moving data from a OLE DB Source to a Flat File Destination.


I have a DateTime field in my database.

My current query returns:
2007-05-21 00:00:00

How can I make it return:
2007-05-21

Thank you!! Smile

Use a derived column to cast the field to DT_DBDATE...

(DT_DBDATE)[YourDateTimeField]|||

I′ve modified the query so it returns only the date.

However, the Flat File Destination always changes it back to a DateTime.

|||

MrHat wrote:

I′ve modified the query so it returns only the date.

However, the Flat File Destination always changes it back to a DateTime.

Yes, you need to define the data type of that column to DT_DBDATE in the flat file connection manager.|||My SQL server destination changes back to DT_DBtimestamp.....in my sql table it has datatype of datetime....but I do not want to display the Time.....just the date....any ideas?|||

JStutz wrote:

My SQL server destination changes back to DT_DBtimestamp.....in my sql table it has datatype of datetime....but I do not want to display the Time.....just the date....any ideas?

Displaying just the time is a simple transact-sql statement using the CONVERT function.

|||

Can you use a SQL Command in your source?

If so, use CONVERT(varchar, <dateField>, 112) in your select list

|||

SQL-PRO wrote:

Can you use a SQL Command in your source?

If so, use CONVERT(varchar, <dateField>, 112) in your select list

Still if that's in your source query, you can't store it that way -- not in SQL Server anyway. (Unless you're storing it in a varchar field.)

DateTime with TimeZone ?

Are there any plans to enhance the DateTime datatype to be able to store a timezone, and provide timezone aware arithmetic functions ?

The lack of timezone support seems a glaring omission - especially given that Microsoft's biggest DB competitor (Oracle) has a timestamp with timezone datatype. At present, you have to code all this yourself in SQL 2005. Is this not something that should be built into the DBMS ?

Thanks,

Andy Mackie

You can store it as UTC.

HTH, Jens Suessmeyer.

datetime vs varchar

If I insert datatime values in a varchar datatype as opposed to datetime,
what am I losing out on ?
Would I be able to perform the same functions against a varchar datatype as
opposed to datetime such as datepart, datediff,etc. ?
Hi Hassan
Why don't you try it and see? Something like this should give you a start:
declare @.today varchar(30)
select @.today = getdate()
select @.today
select dateadd(mm, 1, @.today)
And then read Tibor's excellent article:
http://www.karaszi.com/sqlserver/info_datetime.asp
HTH
Kalen Delaney, SQL Server MVP
www.InsideSQLServer.com
http://blog.kalendelaney.com
"Hassan" <hassan@.test.com> wrote in message
news:uDdP0$EbIHA.748@.TK2MSFTNGP04.phx.gbl...
> If I insert datatime values in a varchar datatype as opposed to datetime,
> what am I losing out on ?
> Would I be able to perform the same functions against a varchar datatype
> as opposed to datetime such as datepart, datediff,etc. ?
>
>
|||Kalen,
Does not seem to be any difference with that example.
"Kalen Delaney" <replies@.public_newsgroups.com> wrote in message
news:ODKGXIFbIHA.5980@.TK2MSFTNGP04.phx.gbl...
> Hi Hassan
> Why don't you try it and see? Something like this should give you a start:
> declare @.today varchar(30)
> select @.today = getdate()
> select @.today
> select dateadd(mm, 1, @.today)
> And then read Tibor's excellent article:
> http://www.karaszi.com/sqlserver/info_datetime.asp
> --
> HTH
> Kalen Delaney, SQL Server MVP
> www.InsideSQLServer.com
> http://blog.kalendelaney.com
>
> "Hassan" <hassan@.test.com> wrote in message
> news:uDdP0$EbIHA.748@.TK2MSFTNGP04.phx.gbl...
>
|||Hassan would have found all that out if he read the article I pointed him
to.
;-)
HTH
Kalen Delaney, SQL Server MVP
www.InsideSQLServer.com
http://blog.kalendelaney.com
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:uB0OLMIbIHA.1376@.TK2MSFTNGP02.phx.gbl...
> Downsides of using varchar include:
> There's nothing stopping you from inserting invalid date (like Feb 30), or
> time values.
> Performing various datetime calculation might mean bad performance, since
> you might end up with a convert on the column side in your predicate.
> You need to decide on a format. If you want to retrieve the value and
> present it in a different format from what it is stored with you have more
> work to do.
> ...
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://sqlblog.com/blogs/tibor_karaszi
>
> "Hassan" <hassan@.test.com> wrote in message
> news:evp1jaFbIHA.4180@.TK2MSFTNGP06.phx.gbl...
>
|||On Feb 11, 6:46Xam, "Hassan" <has...@.test.com> wrote:
> If I insert datatime values in a varchar datatype as opposed to datetime,
> what am I losing out on ?
> Would I be able to perform the same functions against a varchar datatype as
> opposed to datetime such as datepart, datediff,etc. ?
Nothing but you would end up with too much convertions if you want to
manipulate varchars
(ex order by, usage of datediff, dateadd,etc)
Always use proper DATETIME datatype to store dates and let your front
end application do the formation
sql

datetime vs varchar

If I insert datatime values in a varchar datatype as opposed to datetime,
what am I losing out on ?
Would I be able to perform the same functions against a varchar datatype as
opposed to datetime such as datepart, datediff,etc. ?Hi Hassan
Why don't you try it and see? Something like this should give you a start:
declare @.today varchar(30)
select @.today = getdate()
select @.today
select dateadd(mm, 1, @.today)
And then read Tibor's excellent article:
http://www.karaszi.com/sqlserver/info_datetime.asp
--
HTH
Kalen Delaney, SQL Server MVP
www.InsideSQLServer.com
http://blog.kalendelaney.com
"Hassan" <hassan@.test.com> wrote in message
news:uDdP0$EbIHA.748@.TK2MSFTNGP04.phx.gbl...
> If I insert datatime values in a varchar datatype as opposed to datetime,
> what am I losing out on ?
> Would I be able to perform the same functions against a varchar datatype
> as opposed to datetime such as datepart, datediff,etc. ?
>
>|||Kalen,
Does not seem to be any difference with that example.
"Kalen Delaney" <replies@.public_newsgroups.com> wrote in message
news:ODKGXIFbIHA.5980@.TK2MSFTNGP04.phx.gbl...
> Hi Hassan
> Why don't you try it and see? Something like this should give you a start:
> declare @.today varchar(30)
> select @.today = getdate()
> select @.today
> select dateadd(mm, 1, @.today)
> And then read Tibor's excellent article:
> http://www.karaszi.com/sqlserver/info_datetime.asp
> --
> HTH
> Kalen Delaney, SQL Server MVP
> www.InsideSQLServer.com
> http://blog.kalendelaney.com
>
> "Hassan" <hassan@.test.com> wrote in message
> news:uDdP0$EbIHA.748@.TK2MSFTNGP04.phx.gbl...
>> If I insert datatime values in a varchar datatype as opposed to datetime,
>> what am I losing out on ?
>> Would I be able to perform the same functions against a varchar datatype
>> as opposed to datetime such as datepart, datediff,etc. ?
>>
>|||Downsides of using varchar include:
There's nothing stopping you from inserting invalid date (like Feb 30), or time values.
Performing various datetime calculation might mean bad performance, since you might end up with a
convert on the column side in your predicate.
You need to decide on a format. If you want to retrieve the value and present it in a different
format from what it is stored with you have more work to do.
...
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"Hassan" <hassan@.test.com> wrote in message news:evp1jaFbIHA.4180@.TK2MSFTNGP06.phx.gbl...
> Kalen,
> Does not seem to be any difference with that example.
> "Kalen Delaney" <replies@.public_newsgroups.com> wrote in message
> news:ODKGXIFbIHA.5980@.TK2MSFTNGP04.phx.gbl...
>> Hi Hassan
>> Why don't you try it and see? Something like this should give you a start:
>> declare @.today varchar(30)
>> select @.today = getdate()
>> select @.today
>> select dateadd(mm, 1, @.today)
>> And then read Tibor's excellent article:
>> http://www.karaszi.com/sqlserver/info_datetime.asp
>> --
>> HTH
>> Kalen Delaney, SQL Server MVP
>> www.InsideSQLServer.com
>> http://blog.kalendelaney.com
>>
>> "Hassan" <hassan@.test.com> wrote in message news:uDdP0$EbIHA.748@.TK2MSFTNGP04.phx.gbl...
>> If I insert datatime values in a varchar datatype as opposed to datetime, what am I losing out
>> on ?
>> Would I be able to perform the same functions against a varchar datatype as opposed to datetime
>> such as datepart, datediff,etc. ?
>>
>>
>|||Hassan would have found all that out if he read the article I pointed him
to.
;-)
--
HTH
Kalen Delaney, SQL Server MVP
www.InsideSQLServer.com
http://blog.kalendelaney.com
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:uB0OLMIbIHA.1376@.TK2MSFTNGP02.phx.gbl...
> Downsides of using varchar include:
> There's nothing stopping you from inserting invalid date (like Feb 30), or
> time values.
> Performing various datetime calculation might mean bad performance, since
> you might end up with a convert on the column side in your predicate.
> You need to decide on a format. If you want to retrieve the value and
> present it in a different format from what it is stored with you have more
> work to do.
> ...
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://sqlblog.com/blogs/tibor_karaszi
>
> "Hassan" <hassan@.test.com> wrote in message
> news:evp1jaFbIHA.4180@.TK2MSFTNGP06.phx.gbl...
>> Kalen,
>> Does not seem to be any difference with that example.
>> "Kalen Delaney" <replies@.public_newsgroups.com> wrote in message
>> news:ODKGXIFbIHA.5980@.TK2MSFTNGP04.phx.gbl...
>> Hi Hassan
>> Why don't you try it and see? Something like this should give you a
>> start:
>> declare @.today varchar(30)
>> select @.today = getdate()
>> select @.today
>> select dateadd(mm, 1, @.today)
>> And then read Tibor's excellent article:
>> http://www.karaszi.com/sqlserver/info_datetime.asp
>> --
>> HTH
>> Kalen Delaney, SQL Server MVP
>> www.InsideSQLServer.com
>> http://blog.kalendelaney.com
>>
>> "Hassan" <hassan@.test.com> wrote in message
>> news:uDdP0$EbIHA.748@.TK2MSFTNGP04.phx.gbl...
>> If I insert datatime values in a varchar datatype as opposed to
>> datetime, what am I losing out on ?
>> Would I be able to perform the same functions against a varchar
>> datatype as opposed to datetime such as datepart, datediff,etc. ?
>>
>>
>>
>|||On Feb 11, 6:46=A0am, "Hassan" <has...@.test.com> wrote:
> If I insert datatime values in a varchar datatype as opposed to datetime,
> what am I losing out on ?
> Would I be able to perform the same functions against a varchar datatype a=s
> opposed to datetime such as datepart, datediff,etc. ?
Nothing but you would end up with too much convertions if you want to
manipulate varchars
(ex order by, usage of datediff, dateadd,etc)
Always use proper DATETIME datatype to store dates and let your front
end application do the formation|||> Hassan would have found all that out if he read the article I pointed him to.
Ah, that ol' article ;-)
Thanks Kalen :-)
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"Kalen Delaney" <replies@.public_newsgroups.com> wrote in message
news:OkINH5MbIHA.1376@.TK2MSFTNGP02.phx.gbl...
> Hassan would have found all that out if he read the article I pointed him to.
> ;-)
> --
> HTH
> Kalen Delaney, SQL Server MVP
> www.InsideSQLServer.com
> http://blog.kalendelaney.com
>
> "Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in message
> news:uB0OLMIbIHA.1376@.TK2MSFTNGP02.phx.gbl...
>> Downsides of using varchar include:
>> There's nothing stopping you from inserting invalid date (like Feb 30), or time values.
>> Performing various datetime calculation might mean bad performance, since you might end up with a
>> convert on the column side in your predicate.
>> You need to decide on a format. If you want to retrieve the value and present it in a different
>> format from what it is stored with you have more work to do.
>> ...
>> --
>> Tibor Karaszi, SQL Server MVP
>> http://www.karaszi.com/sqlserver/default.asp
>> http://sqlblog.com/blogs/tibor_karaszi
>>
>> "Hassan" <hassan@.test.com> wrote in message news:evp1jaFbIHA.4180@.TK2MSFTNGP06.phx.gbl...
>> Kalen,
>> Does not seem to be any difference with that example.
>> "Kalen Delaney" <replies@.public_newsgroups.com> wrote in message
>> news:ODKGXIFbIHA.5980@.TK2MSFTNGP04.phx.gbl...
>> Hi Hassan
>> Why don't you try it and see? Something like this should give you a start:
>> declare @.today varchar(30)
>> select @.today = getdate()
>> select @.today
>> select dateadd(mm, 1, @.today)
>> And then read Tibor's excellent article:
>> http://www.karaszi.com/sqlserver/info_datetime.asp
>> --
>> HTH
>> Kalen Delaney, SQL Server MVP
>> www.InsideSQLServer.com
>> http://blog.kalendelaney.com
>>
>> "Hassan" <hassan@.test.com> wrote in message news:uDdP0$EbIHA.748@.TK2MSFTNGP04.phx.gbl...
>> If I insert datatime values in a varchar datatype as opposed to datetime, what am I losing out
>> on ?
>> Would I be able to perform the same functions against a varchar datatype as opposed to
>> datetime such as datepart, datediff,etc. ?
>>
>>
>>
>>
>

DateTime variables

Hi all
Sorry if this is in the wrong place, please tell me if it is.
I've got a SQL 2000 database and I'm having problems selecting rows where
the value of a datetime column (with date and time) has to be less than
todays date with no time.
I can't work out how to do this. I've tried:
PrintedDate contains date and time
dDateOfVisit is todays date in dd/MM/yyyy format
SELECT DISTINCT Reference
FROM cdNotes
WHERE (StoreCode = 'CET719')
AND (ItemStatusId = 1)
AND convert(varchar, PrintedDate, 113) <= convert(datetime, '" &
dDateOfVisit & "', 103)
but it doesn't return any rows.
As I can't figure this out I decided to try and remove the times from the
datetime columns in my database. And to change the triggers to only insert
dates with no times.
CREATE TRIGGER [stsDateInsert] ON dbo.cdNotes
AFTER INSERT
AS
update cdNotes set DownloadedDate = GETDATE() where [index] in
(
SELECT inserted.[index] FROM inserted
)
Im having a bad day as I cant figure out how to remove the times from the
trigger update either.
Can someone please tell me how. Thanks very much.
Kind Regards
Darren RhymerDarren,
An expression that is true when the datetime column dt is
less than today's date with no time is
dt < dateadd(day,datediff(day,0,getdate()),0)
The messy expression on the right is simply today at midnight, as
a datetime type, so it's just what you want if you need today's
date "with no time part" in a trigger or elsewhere. You might also
consider this as a DEFAULT value for the column, which might
avoid the need for a trigger.
To get the date-only part of a different value than getdate(), you
can use the same idea: dateadd(day,datediff(day,0,anyDateTime),
0).
I won't guess just what you need to type into your query, but I will
mention that converting dDateOfVisit to a datetime expression would
be done with
convert(datetime,dDateOfVisit,103)
if that column is a varchar value with format dd/mm/yyyy. What you
have below tries to convert the string
"& dDateOfVisit & "
(with the double quotes, ampersands, spaces, and the word dDateOfVisit
as part of the string). That's not a date, and you should get an error. If
you don't, then you haven't shown us the exact query you are executing.
More likely than not, you'll have better luck if you can change your
table structure so that dates are stored in datetime columns, not in
string columns.
Your query doesn't seem to have anything to do with today's date,
so to select rows where a column value is "less than today's date"
you'll need getdate() somewhere in an expression like the one at
the top of this reply, but I don't know which of the two date columns
you need to compare with today.
Steve Kass
Drew University
Darren Rhymer wrote:

>Hi all
>Sorry if this is in the wrong place, please tell me if it is.
>I've got a SQL 2000 database and I'm having problems selecting rows where
>the value of a datetime column (with date and time) has to be less than
>todays date with no time.
>I can't work out how to do this. I've tried:
>PrintedDate contains date and time
>dDateOfVisit is todays date in dd/MM/yyyy format
>SELECT DISTINCT Reference
>FROM cdNotes
>WHERE (StoreCode = 'CET719')
>AND (ItemStatusId = 1)
>AND convert(varchar, PrintedDate, 113) <= convert(datetime, '" &
>dDateOfVisit & "', 103)
>but it doesn't return any rows.
>As I can't figure this out I decided to try and remove the times from the
>datetime columns in my database. And to change the triggers to only insert
>dates with no times.
>CREATE TRIGGER [stsDateInsert] ON dbo.cdNotes
>AFTER INSERT
>AS
>update cdNotes set DownloadedDate = GETDATE() where [index] in
>(
>SELECT inserted.[index] FROM inserted
> )
>Im having a bad day as I cant figure out how to remove the times from the
>trigger update either.
>Can someone please tell me how. Thanks very much.
>Kind Regards
>Darren Rhymer
>|||Darren Rhymer (darren_rhymer@.hotmail.com.no.spam) writes:
> Sorry if this is in the wrong place, please tell me if it is.
> I've got a SQL 2000 database and I'm having problems selecting rows where
> the value of a datetime column (with date and time) has to be less than
> todays date with no time.
> I can't work out how to do this. I've tried:
> PrintedDate contains date and time
> dDateOfVisit is todays date in dd/MM/yyyy format
> SELECT DISTINCT Reference
> FROM cdNotes
> WHERE (StoreCode = 'CET719')
> AND (ItemStatusId = 1)
> AND convert(varchar, PrintedDate, 113) <= convert(datetime, '" &
> dDateOfVisit & "', 103)
I assume that this is a SELECT send an SQL statement from a client,
the apparence of & and # indicate so.
Never embed values directly into the SQL command, but use parameter
markers instead, and then use a parameter object. The client API will
then convert the date according to the regional settings and pass the
date as a binary value, then you will not have to use convert for the
date value on the SQL Server side.
As I don't know which client API you are using I cannot give the exact
details on how to do this.
You should also avoid wrapping columns into expressions, as this preclude
use of the any index on the column, or at least the best use of the index.
Why convert the date to format 113 is beyond me, as this format includes
the time portion as well. If you want to say:
WHERE (date porttion of PrintedDate) <= dDateOfVisit
this is better:
WHERE PrintedDate < dateadd(DAY,1, @.dDateofVisit)

> As I can't figure this out I decided to try and remove the times from the
> datetime columns in my database.
If you do not need the times that's an excellent idea!
The idiom to strip a datetime value of a its time is
convert(char(8), value, 112)
Format 112 is YYYYMMDD which has the property of always being interpreted
in the one and same way in SQL Server.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Hi chaps
Thanks very much for the repsonses they've been most interesting. I must
now apoligise for me leading you somewhere in the wrong direction on the 1st
part.
1) This is where Im trying to select from the database all records with
databasedate <= specified date. I failed to say, sorry, that this is being
done in VB.NET. My sql query looks like:
sql = "SELECT distinct reference from CDNotes"
sql = sql & " WHERE StoreCode = '" & txtStoreCode.Text
sql = sql & "' AND ItemStatusId = " & ItemStatus.Printed
sql = sql & " AND PrintedDate < dateadd(DAY, 1, '" & dDateOfVisit & "')"
which returns THE CORRECT RESULTS. (Thanks Erland for spotting this)
2) This is where im trying to remove the times from the existing datetime
columns in the database.
I have
UPDATE cdNotes
SET DownloadedDate = CONVERT(char(8), DownloadedDate, 112)
which works, thanks very much.
3) I need to remove the time part from the datetime when I'm inserting
GETDATE into the column after the status has changed.
CREATE TRIGGER [stsDateChange] ON dbo.cdNotes
AFTER UPDATE
AS
update cdNotes set PrintedDate = CONVERT(char(8), GETDATE(), 112) where
[index] in
(
SELECT inserted.[index] FROM inserted JOIN deleted ON inserted.[index]
=deleted.[index]
WHERE inserted.itemStatusId <> deleted.itemStatusId
AND inserted.itemStatusId = 2
)
update cdNotes set ScannedDate = CONVERT(char(8), GETDATE(), 112) where
[index] in
(
SELECT inserted.[index] FROM inserted JOIN deleted ON inserted.[index]
=deleted.[index]
WHERE inserted.itemStatusId <> deleted.itemStatusId
AND (inserted.itemStatusId = 3 OR inserted.itemStatusId = 4)
)
This now works aswell.
Many thanks to you two, cheers
Darren Rhymer
"Darren Rhymer" wrote:

> Hi all
> Sorry if this is in the wrong place, please tell me if it is.
> I've got a SQL 2000 database and I'm having problems selecting rows where
> the value of a datetime column (with date and time) has to be less than
> todays date with no time.
> I can't work out how to do this. I've tried:
> PrintedDate contains date and time
> dDateOfVisit is todays date in dd/MM/yyyy format
> SELECT DISTINCT Reference
> FROM cdNotes
> WHERE (StoreCode = 'CET719')
> AND (ItemStatusId = 1)
> AND convert(varchar, PrintedDate, 113) <= convert(datetime, '" &
> dDateOfVisit & "', 103)
> but it doesn't return any rows.
> As I can't figure this out I decided to try and remove the times from the
> datetime columns in my database. And to change the triggers to only inser
t
> dates with no times.
> CREATE TRIGGER [stsDateInsert] ON dbo.cdNotes
> AFTER INSERT
> AS
> update cdNotes set DownloadedDate = GETDATE() where [index] in
> (
> SELECT inserted.[index] FROM inserted
> )
> Im having a bad day as I cant figure out how to remove the times from the
> trigger update either.
> Can someone please tell me how. Thanks very much.
> Kind Regards
> Darren Rhymer|||The fastest way to strip date is:
DATEADD(DAY, DATEDIFF(DAY, <DateTimeGoesHere>, 0), <DateTimeGoesHere> )
<DateTimeGoesHere> can be a column name, variable, or getdate().
Both <DateTimeGoesHere> have to be the same. This formula calculates the
number of days from your datetime to 19000101. (Due to the parameter
ordering, this is a negative number.) Then, it adds the negative number
(i.e. subtracts it) from your datetime leaving only the time.
The fastest way to strip time is:
CAST(DATEDIFF(DAY,0, <DateTimeGoesHere> ) as datetime)
<DateTimeGoesHere> can be a column name, variable, or getdate().
If you want today at midnight:
CAST(DATEDIFF(DAY,0,getdate()) as datetime)
If you want tomorrow at midnight:
CAST(DATEDIFF(DAY,0,getdate())+1 as datetime)
(This can be used to include data that occurred anytime today, regardless of
time.)
When dealing with datetimes, always consider both portions. If the client
sends a date and you want anything that occurs on that date:
dtColumn >= @.MyDate and
dtColumn < CAST(DATEDIFF(DAY,0,@.MyDate)+1 as datetime)
Had the client sent the date and time, then:
dtColumn >= CAST(DATEDIFF(DAY,0,@.MyDate) as datetime) and
dtColumn < CAST(DATEDIFF(DAY,0,@.MyDate)+1 as datetime)
Other posters are correct, you want to avoid wrapping functions around a
column name in a WHERE clause if possible.
And, you should avoid converting datetime to a character string (i.e.
char(8)) and then converting it to datetime containing just a date or a time
.
It's not effecient.
Hope that helps,
Joe
"Darren Rhymer" wrote:

> Hi all
> Sorry if this is in the wrong place, please tell me if it is.
> I've got a SQL 2000 database and I'm having problems selecting rows where
> the value of a datetime column (with date and time) has to be less than
> todays date with no time.
> I can't work out how to do this. I've tried:
> PrintedDate contains date and time
> dDateOfVisit is todays date in dd/MM/yyyy format
> SELECT DISTINCT Reference
> FROM cdNotes
> WHERE (StoreCode = 'CET719')
> AND (ItemStatusId = 1)
> AND convert(varchar, PrintedDate, 113) <= convert(datetime, '" &
> dDateOfVisit & "', 103)
> but it doesn't return any rows.
> As I can't figure this out I decided to try and remove the times from the
> datetime columns in my database. And to change the triggers to only inser
t
> dates with no times.
> CREATE TRIGGER [stsDateInsert] ON dbo.cdNotes
> AFTER INSERT
> AS
> update cdNotes set DownloadedDate = GETDATE() where [index] in
> (
> SELECT inserted.[index] FROM inserted
> )
> Im having a bad day as I cant figure out how to remove the times from the
> trigger update either.
> Can someone please tell me how. Thanks very much.
> Kind Regards
> Darren Rhymer|||P.S. Seeing we're talking about dates and times...
DateTime of 23:59:59.997 is the highest stored time value.
23:59:59.998 is rounded down to .997.
23:59:59.999 is rounded up to the next day.
Just be careful if you concatenate a datetime range such as
>= 00:00:00.000 and <= 23:59:59.999 as the .999 will round the datetime up to the ne
xt day at midnight.|||Joe
Thanks very much for you reply. Makes interesting reading.
At the moment one of my triggers to update the scanned date column with
todays date looks like:
update cdNotes set ScannedDate = CONVERT(char(8), GETDATE(), 112) where
[index] in
(
SELECT inserted.[index] FROM inserted JOIN deleted ON inserted.[index]
=deleted.[index]
WHERE inserted.itemStatusId <> deleted.itemStatusId
AND (inserted.itemStatusId = 3 OR inserted.itemStatusId = 4)
)
Are you saying I should somehow replace the
CONVERT(char(8), GETDATE(), 112)
with
DATEDIFF(DAY,0, GETDATE()
Thanks again
Darren
Kind Regards
Darren Rhymer
"Joe from WI" wrote:
> The fastest way to strip date is:
> DATEADD(DAY, DATEDIFF(DAY, <DateTimeGoesHere>, 0), <DateTimeGoesHere> )
> <DateTimeGoesHere> can be a column name, variable, or getdate().
> Both <DateTimeGoesHere> have to be the same. This formula calculates the
> number of days from your datetime to 19000101. (Due to the parameter
> ordering, this is a negative number.) Then, it adds the negative number
> (i.e. subtracts it) from your datetime leaving only the time.
> The fastest way to strip time is:
> CAST(DATEDIFF(DAY,0, <DateTimeGoesHere> ) as datetime)
> <DateTimeGoesHere> can be a column name, variable, or getdate().
> If you want today at midnight:
> CAST(DATEDIFF(DAY,0,getdate()) as datetime)
> If you want tomorrow at midnight:
> CAST(DATEDIFF(DAY,0,getdate())+1 as datetime)
> (This can be used to include data that occurred anytime today, regardless
of
> time.)
>
> When dealing with datetimes, always consider both portions. If the client
> sends a date and you want anything that occurs on that date:
> dtColumn >= @.MyDate and
> dtColumn < CAST(DATEDIFF(DAY,0,@.MyDate)+1 as datetime)
> Had the client sent the date and time, then:
> dtColumn >= CAST(DATEDIFF(DAY,0,@.MyDate) as datetime) and
> dtColumn < CAST(DATEDIFF(DAY,0,@.MyDate)+1 as datetime)
> Other posters are correct, you want to avoid wrapping functions around a
> column name in a WHERE clause if possible.
> And, you should avoid converting datetime to a character string (i.e.
> char(8)) and then converting it to datetime containing just a date or a ti
me.
> It's not effecient.
> Hope that helps,
> Joe
> "Darren Rhymer" wrote:
>|||Darren Rhymer (darren_rhymer@.hotmail.com.no.spam) writes:
> Are you saying I should somehow replace the
> CONVERT(char(8), GETDATE(), 112)
> with
> DATEDIFF(DAY,0, GETDATE())
Both yield the same result, so it's a matter of taste which one to choose.
I prefer the first, because, well, if you need to present the date in
some output, you can use the same format. Overall, when you work with
date literals, you use character strings, whereas using numeric types
for dates feels more akward to me. But it would be difficult to say
that these are any compelling reasons.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||With all due respect, in this example, the datetime is not being used as
ouput. Darren wants the strip the time from a datetime data type and update
a datetime column.
Someone ran performance tests on various datetime conversions. (I cannot
remember who and I appolize to the person who did it. If you search for dat
e
or datetime, you might be able to find the post and the link to the test
results.)
Converting a datetime to a string and then to a datetime again is one the
slowest performers. (I suggest you test it on your hardware in query
analyzer using a loop and variables.) Yes, we're talking microseconds per
execution but on a heavily loaded box it all adds up.
Based on those tests, the following is the fastest because it is pure
integer arithmetic which by the way is always the fastest way to do things i
n
a computer.
CAST(DATEDIFF(DAY,0, <DateTimeGoesHere> ) as datetime)
So yes, if you want the best performing code, the trigger should use
CAST(DATEDIFF(DAY,0,getdate()) as datetime)
(P.S. You need the outer cast as datetime because datediff returns an
integer value.)
Also, I have a correction to my earlier post where the client sends just the
date. The upper limit could and probably should do a simple dateadd.
dtColumn < DATEADD(DAY,1,@.MyDate)
Just my two cents,
Joe
"Erland Sommarskog" wrote:

> Darren Rhymer (darren_rhymer@.hotmail.com.no.spam) writes:
> Both yield the same result, so it's a matter of taste which one to choose.
> I prefer the first, because, well, if you need to present the date in
> some output, you can use the same format. Overall, when you work with
> date literals, you use character strings, whereas using numeric types
> for dates feels more akward to me. But it would be difficult to say
> that these are any compelling reasons.
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx
>|||
Joe from WI wrote:

>With all due respect, in this example, the datetime is not being used as
>ouput. Darren wants the strip the time from a datetime data type and updat
e
>a datetime column.
>Someone ran performance tests on various datetime conversions. (I cannot
>remember who and I appolize to the person who did it. If you search for da
te
>or datetime, you might be able to find the post and the link to the test
>results.)
>
Here's the post you may be talking about :
http://groups.google.com/groups?q=b...100000+datetime
Steve Kass
Drew University
>Converting a datetime to a string and then to a datetime again is one the
>slowest performers. (I suggest you test it on your hardware in query
>analyzer using a loop and variables.) Yes, we're talking microseconds per
>execution but on a heavily loaded box it all adds up.
>Based on those tests, the following is the fastest because it is pure
>integer arithmetic which by the way is always the fastest way to do things
in
>a computer.
>CAST(DATEDIFF(DAY,0, <DateTimeGoesHere> ) as datetime)
>So yes, if you want the best performing code, the trigger should use
>CAST(DATEDIFF(DAY,0,getdate()) as datetime)
>(P.S. You need the outer cast as datetime because datediff returns an
>integer value.)
>Also, I have a correction to my earlier post where the client sends just th
e
>date. The upper limit could and probably should do a simple dateadd.
>dtColumn < DATEADD(DAY,1,@.MyDate)
>Just my two cents,
>Joe
>"Erland Sommarskog" wrote:
>
>

DateTime variable problem

Hi,
The followng snippet runs OK in SQL Query analyser when a literal date
'1/11/2006' is used for the first date comparision
When local variable @.StartDate is used instead it runs on forever (I think,
certainly an order of magnitude longer)
(I added the set dateformat dmy and switched to the numeric date format in
an effort to solve this.
Ideally I want to run with '1-Nov-2006' which for some reason runs faster
than the numeric version.)
Any ideas what I am doing wrong?
thanks
Bob
declare @.StartDate datetime
declare @.EndDate datetime
set dateformat dmy
set @.StartDate='1/11/2006'
set @.EndDate = '2/11/2006'
create Table #Temp (icp_id int)
insert into #Temp select distinct mh.icp_id as icp_id FROM routehistory rh
inner join metershistory mh
ON rh.id = mh.routehistory_id
inner join icps i on mh.icp_id=i.id
WHERE rh.type = 1 and i.company_id =1
and rh.read_date>= @.StartDate and rh.read_date < '2/11/2006' and
mh.cant_read_code is null
It will be because the optimiser is allowing for different values in the
variable. With the literal it knows to use the date index - with the variable
it is allowing for a large date range.
Look at the query plan and change the query (mayne a subquery for the date)
or give a hint or maybe include the other columns in the date index to make
it covering.
Maybe something like
FROM (select * from routehistory where read_date between @.StartDate and
@.EndDate) rh
.....
"Bob" wrote:

> Hi,
> The followng snippet runs OK in SQL Query analyser when a literal date
> '1/11/2006' is used for the first date comparision
> When local variable @.StartDate is used instead it runs on forever (I think,
> certainly an order of magnitude longer)
> (I added the set dateformat dmy and switched to the numeric date format in
> an effort to solve this.
> Ideally I want to run with '1-Nov-2006' which for some reason runs faster
> than the numeric version.)
> Any ideas what I am doing wrong?
> thanks
> Bob
> declare @.StartDate datetime
> declare @.EndDate datetime
> set dateformat dmy
> set @.StartDate='1/11/2006'
> set @.EndDate = '2/11/2006'
> create Table #Temp (icp_id int)
> insert into #Temp select distinct mh.icp_id as icp_id FROM routehistory rh
> inner join metershistory mh
> ON rh.id = mh.routehistory_id
> inner join icps i on mh.icp_id=i.id
> WHERE rh.type = 1 and i.company_id =1
> and rh.read_date>= @.StartDate and rh.read_date < '2/11/2006' and
> mh.cant_read_code is null
>
>
|||Bob
I have a couple of questions
1) Do you have an index (probably CI would be good choice) on read_date
column?
2) What happened if you change date format to YYYYMMDD and don't use SET
DATEFORMAT
"Bob" <bob@.nowhere.com> wrote in message
news:uRoiCglIHHA.4000@.TK2MSFTNGP06.phx.gbl...
> Hi,
> The followng snippet runs OK in SQL Query analyser when a literal date
> '1/11/2006' is used for the first date comparision
> When local variable @.StartDate is used instead it runs on forever (I
> think,
> certainly an order of magnitude longer)
> (I added the set dateformat dmy and switched to the numeric date format in
> an effort to solve this.
> Ideally I want to run with '1-Nov-2006' which for some reason runs faster
> than the numeric version.)
> Any ideas what I am doing wrong?
> thanks
> Bob
> declare @.StartDate datetime
> declare @.EndDate datetime
> set dateformat dmy
> set @.StartDate='1/11/2006'
> set @.EndDate = '2/11/2006'
> create Table #Temp (icp_id int)
> insert into #Temp select distinct mh.icp_id as icp_id FROM routehistory
> rh
> inner join metershistory mh
> ON rh.id = mh.routehistory_id
> inner join icps i on mh.icp_id=i.id
> WHERE rh.type = 1 and i.company_id =1
> and rh.read_date>= @.StartDate and rh.read_date < '2/11/2006' and
> mh.cant_read_code is null
>
|||Bob,
I think that you are being encountering what has become know as 'parameter
sniffing'.
You may wish to review these articles:
Stored Procedure -Parameter Sniffing
http://blogs.msdn.com/queryoptteam/archive/2006/03/31/565991.aspx
http://tinyurl.com/f9r2
http://sqlblogcasts.com/blogs/tonyrogerson/archive/2006/05/17/444.aspx
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
You can't help someone get up a hill without getting a little closer to the
top yourself.
- H. Norman Schwarzkopf
"Bob" <bob@.nowhere.com> wrote in message
news:uRoiCglIHHA.4000@.TK2MSFTNGP06.phx.gbl...
> Hi,
> The followng snippet runs OK in SQL Query analyser when a literal date
> '1/11/2006' is used for the first date comparision
> When local variable @.StartDate is used instead it runs on forever (I
> think,
> certainly an order of magnitude longer)
> (I added the set dateformat dmy and switched to the numeric date format in
> an effort to solve this.
> Ideally I want to run with '1-Nov-2006' which for some reason runs faster
> than the numeric version.)
> Any ideas what I am doing wrong?
> thanks
> Bob
> declare @.StartDate datetime
> declare @.EndDate datetime
> set dateformat dmy
> set @.StartDate='1/11/2006'
> set @.EndDate = '2/11/2006'
> create Table #Temp (icp_id int)
> insert into #Temp select distinct mh.icp_id as icp_id FROM routehistory
> rh
> inner join metershistory mh
> ON rh.id = mh.routehistory_id
> inner join icps i on mh.icp_id=i.id
> WHERE rh.type = 1 and i.company_id =1
> and rh.read_date>= @.StartDate and rh.read_date < '2/11/2006' and
> mh.cant_read_code is null
>
|||Hi All,
Thank you for your replies.
I won't pretend I understand Parameter sniffing.
What I have done is put the query into a sproc which was my end goal anyway
and I am tuning that up.
regards
Bob

DateTime variable problem

Hi,
The followng snippet runs OK in SQL Query analyser when a literal date
'1/11/2006' is used for the first date comparision
When local variable @.StartDate is used instead it runs on forever (I think,
certainly an order of magnitude longer)
(I added the set dateformat dmy and switched to the numeric date format in
an effort to solve this.
Ideally I want to run with '1-Nov-2006' which for some reason runs faster
than the numeric version.)
Any ideas what I am doing wrong?
thanks
Bob
declare @.StartDate datetime
declare @.EndDate datetime
set dateformat dmy
set @.StartDate='1/11/2006'
set @.EndDate = '2/11/2006'
create Table #Temp (icp_id int)
insert into #Temp select distinct mh.icp_id as icp_id FROM routehistory rh
inner join metershistory mh
ON rh.id = mh.routehistory_id
inner join icps i on mh.icp_id=i.id
WHERE rh.type = 1 and i.company_id =1
and rh.read_date>= @.StartDate and rh.read_date < '2/11/2006' and
mh.cant_read_code is nullIt will be because the optimiser is allowing for different values in the
variable. With the literal it knows to use the date index - with the variable
it is allowing for a large date range.
Look at the query plan and change the query (mayne a subquery for the date)
or give a hint or maybe include the other columns in the date index to make
it covering.
Maybe something like
FROM (select * from routehistory where read_date between @.StartDate and
@.EndDate) rh
....
"Bob" wrote:
> Hi,
> The followng snippet runs OK in SQL Query analyser when a literal date
> '1/11/2006' is used for the first date comparision
> When local variable @.StartDate is used instead it runs on forever (I think,
> certainly an order of magnitude longer)
> (I added the set dateformat dmy and switched to the numeric date format in
> an effort to solve this.
> Ideally I want to run with '1-Nov-2006' which for some reason runs faster
> than the numeric version.)
> Any ideas what I am doing wrong?
> thanks
> Bob
> declare @.StartDate datetime
> declare @.EndDate datetime
> set dateformat dmy
> set @.StartDate='1/11/2006'
> set @.EndDate = '2/11/2006'
> create Table #Temp (icp_id int)
> insert into #Temp select distinct mh.icp_id as icp_id FROM routehistory rh
> inner join metershistory mh
> ON rh.id = mh.routehistory_id
> inner join icps i on mh.icp_id=i.id
> WHERE rh.type = 1 and i.company_id =1
> and rh.read_date>= @.StartDate and rh.read_date < '2/11/2006' and
> mh.cant_read_code is null
>
>|||Bob
I have a couple of questions
1) Do you have an index (probably CI would be good choice) on read_date
column?
2) What happened if you change date format to YYYYMMDD and don't use SET
DATEFORMAT
"Bob" <bob@.nowhere.com> wrote in message
news:uRoiCglIHHA.4000@.TK2MSFTNGP06.phx.gbl...
> Hi,
> The followng snippet runs OK in SQL Query analyser when a literal date
> '1/11/2006' is used for the first date comparision
> When local variable @.StartDate is used instead it runs on forever (I
> think,
> certainly an order of magnitude longer)
> (I added the set dateformat dmy and switched to the numeric date format in
> an effort to solve this.
> Ideally I want to run with '1-Nov-2006' which for some reason runs faster
> than the numeric version.)
> Any ideas what I am doing wrong?
> thanks
> Bob
> declare @.StartDate datetime
> declare @.EndDate datetime
> set dateformat dmy
> set @.StartDate='1/11/2006'
> set @.EndDate = '2/11/2006'
> create Table #Temp (icp_id int)
> insert into #Temp select distinct mh.icp_id as icp_id FROM routehistory
> rh
> inner join metershistory mh
> ON rh.id = mh.routehistory_id
> inner join icps i on mh.icp_id=i.id
> WHERE rh.type = 1 and i.company_id =1
> and rh.read_date>= @.StartDate and rh.read_date < '2/11/2006' and
> mh.cant_read_code is null
>|||Bob,
I think that you are being encountering what has become know as 'parameter
sniffing'.
You may wish to review these articles:
Stored Procedure -Parameter Sniffing
http://blogs.msdn.com/queryoptteam/archive/2006/03/31/565991.aspx
http://tinyurl.com/f9r2
http://sqlblogcasts.com/blogs/tonyrogerson/archive/2006/05/17/444.aspx
--
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
You can't help someone get up a hill without getting a little closer to the
top yourself.
- H. Norman Schwarzkopf
"Bob" <bob@.nowhere.com> wrote in message
news:uRoiCglIHHA.4000@.TK2MSFTNGP06.phx.gbl...
> Hi,
> The followng snippet runs OK in SQL Query analyser when a literal date
> '1/11/2006' is used for the first date comparision
> When local variable @.StartDate is used instead it runs on forever (I
> think,
> certainly an order of magnitude longer)
> (I added the set dateformat dmy and switched to the numeric date format in
> an effort to solve this.
> Ideally I want to run with '1-Nov-2006' which for some reason runs faster
> than the numeric version.)
> Any ideas what I am doing wrong?
> thanks
> Bob
> declare @.StartDate datetime
> declare @.EndDate datetime
> set dateformat dmy
> set @.StartDate='1/11/2006'
> set @.EndDate = '2/11/2006'
> create Table #Temp (icp_id int)
> insert into #Temp select distinct mh.icp_id as icp_id FROM routehistory
> rh
> inner join metershistory mh
> ON rh.id = mh.routehistory_id
> inner join icps i on mh.icp_id=i.id
> WHERE rh.type = 1 and i.company_id =1
> and rh.read_date>= @.StartDate and rh.read_date < '2/11/2006' and
> mh.cant_read_code is null
>|||Hi All,
Thank you for your replies.
I won't pretend I understand Parameter sniffing.
What I have done is put the query into a sproc which was my end goal anyway
and I am tuning that up.
regards
Bob

DateTime variable problem

Hi,
The followng snippet runs OK in SQL Query analyser when a literal date
'1/11/2006' is used for the first date comparision
When local variable @.StartDate is used instead it runs on forever (I think,
certainly an order of magnitude longer)
(I added the set dateformat dmy and switched to the numeric date format in
an effort to solve this.
Ideally I want to run with '1-Nov-2006' which for some reason runs faster
than the numeric version.)
Any ideas what I am doing wrong?
thanks
Bob
declare @.StartDate datetime
declare @.EndDate datetime
set dateformat dmy
set @.StartDate='1/11/2006'
set @.EndDate = '2/11/2006'
create Table #Temp (icp_id int)
insert into #Temp select distinct mh.icp_id as icp_id FROM routehistory rh
inner join metershistory mh
ON rh.id = mh.routehistory_id
inner join icps i on mh.icp_id=i.id
WHERE rh.type = 1 and i.company_id =1
and rh.read_date>= @.StartDate and rh.read_date < '2/11/2006' and
mh.cant_read_code is nullIt will be because the optimiser is allowing for different values in the
variable. With the literal it knows to use the date index - with the variabl
e
it is allowing for a large date range.
Look at the query plan and change the query (mayne a subquery for the date)
or give a hint or maybe include the other columns in the date index to make
it covering.
Maybe something like
FROM (select * from routehistory where read_date between @.StartDate and
@.EndDate) rh
....
"Bob" wrote:

> Hi,
> The followng snippet runs OK in SQL Query analyser when a literal date
> '1/11/2006' is used for the first date comparision
> When local variable @.StartDate is used instead it runs on forever (I think
,
> certainly an order of magnitude longer)
> (I added the set dateformat dmy and switched to the numeric date format in
> an effort to solve this.
> Ideally I want to run with '1-Nov-2006' which for some reason runs faster
> than the numeric version.)
> Any ideas what I am doing wrong?
> thanks
> Bob
> declare @.StartDate datetime
> declare @.EndDate datetime
> set dateformat dmy
> set @.StartDate='1/11/2006'
> set @.EndDate = '2/11/2006'
> create Table #Temp (icp_id int)
> insert into #Temp select distinct mh.icp_id as icp_id FROM routehistory
rh
> inner join metershistory mh
> ON rh.id = mh.routehistory_id
> inner join icps i on mh.icp_id=i.id
> WHERE rh.type = 1 and i.company_id =1
> and rh.read_date>= @.StartDate and rh.read_date < '2/11/2006' and
> mh.cant_read_code is null
>
>|||Bob
I have a couple of questions
1) Do you have an index (probably CI would be good choice) on read_date
column?
2) What happened if you change date format to YYYYMMDD and don't use SET
DATEFORMAT
"Bob" <bob@.nowhere.com> wrote in message
news:uRoiCglIHHA.4000@.TK2MSFTNGP06.phx.gbl...
> Hi,
> The followng snippet runs OK in SQL Query analyser when a literal date
> '1/11/2006' is used for the first date comparision
> When local variable @.StartDate is used instead it runs on forever (I
> think,
> certainly an order of magnitude longer)
> (I added the set dateformat dmy and switched to the numeric date format in
> an effort to solve this.
> Ideally I want to run with '1-Nov-2006' which for some reason runs faster
> than the numeric version.)
> Any ideas what I am doing wrong?
> thanks
> Bob
> declare @.StartDate datetime
> declare @.EndDate datetime
> set dateformat dmy
> set @.StartDate='1/11/2006'
> set @.EndDate = '2/11/2006'
> create Table #Temp (icp_id int)
> insert into #Temp select distinct mh.icp_id as icp_id FROM routehistory
> rh
> inner join metershistory mh
> ON rh.id = mh.routehistory_id
> inner join icps i on mh.icp_id=i.id
> WHERE rh.type = 1 and i.company_id =1
> and rh.read_date>= @.StartDate and rh.read_date < '2/11/2006' and
> mh.cant_read_code is null
>|||Bob,
I think that you are being encountering what has become know as 'parameter
sniffing'.
You may wish to review these articles:
Stored Procedure -Parameter Sniffing
http://blogs.msdn.com/queryoptteam/.../31/565991.aspx
http://tinyurl.com/f9r2
http://sqlblogcasts.com/blogs/tonyr.../05/17/444.aspx
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
You can't help someone get up a hill without getting a little closer to the
top yourself.
- H. Norman Schwarzkopf
"Bob" <bob@.nowhere.com> wrote in message
news:uRoiCglIHHA.4000@.TK2MSFTNGP06.phx.gbl...
> Hi,
> The followng snippet runs OK in SQL Query analyser when a literal date
> '1/11/2006' is used for the first date comparision
> When local variable @.StartDate is used instead it runs on forever (I
> think,
> certainly an order of magnitude longer)
> (I added the set dateformat dmy and switched to the numeric date format in
> an effort to solve this.
> Ideally I want to run with '1-Nov-2006' which for some reason runs faster
> than the numeric version.)
> Any ideas what I am doing wrong?
> thanks
> Bob
> declare @.StartDate datetime
> declare @.EndDate datetime
> set dateformat dmy
> set @.StartDate='1/11/2006'
> set @.EndDate = '2/11/2006'
> create Table #Temp (icp_id int)
> insert into #Temp select distinct mh.icp_id as icp_id FROM routehistory
> rh
> inner join metershistory mh
> ON rh.id = mh.routehistory_id
> inner join icps i on mh.icp_id=i.id
> WHERE rh.type = 1 and i.company_id =1
> and rh.read_date>= @.StartDate and rh.read_date < '2/11/2006' and
> mh.cant_read_code is null
>sql

DateTime Values in SQL Express ASPNETDB.MDF

greets again folks,

The values LastLoginDate and LastActivityDate in my SQl Express membership dBase are always off.

The date is usually correct but the time is always hours off.

Is there some way to get the time part of the DateTime to be correct?

Do I have to write code to set the time when the user logs in?

Thanks a mil!

It sounds as if GetUtcDate() is being called instead of GetDate. GetUTCDate records the UTC or GMT date time whereas GetDate() get the local date time.

|||

hypercode:

greets again folks,

The values LastLoginDate and LastActivityDate in my SQl Express membership dBase are always off.

The date is usually correct but the time is always hours off.

Is there some way to get the time part of the DateTime to be correct?

Do I have to write code to set the time when the user logs in?

Thanks a mil!

check database coumn type ... is it set to DateTime ....

|||

Kamrul,

Although unlikely, the column does not have to be a DateTime to have GetDate assigned to it. E.g.SELECTCONVERT(VARCHAR(20),GetDate(), 113) returned "19 Apr 2007 17:07:06". but could have inserted the valud into a CHAR(20) column.

|||

The date is OFF in the ASPNETDB itself.

Beoroe I write any code to retireve the values, they are already in the dBase off to begin with.

Is there some way to tell the dBase to record the correct times?

|||

Look in the table definition, do the collumns have the default property change the GetUtcDate() to GetDate(). Do the same in the stored procedures and all date/time from then will be in local rather than universal time.

Incidentally was the time an exact number of hours off from the server time?

|||

" Look in the table definition, do the collumns have the default property change the GetUtcDate() to GetDate(). Do the same in the stored procedures and all date/time from then will be in local rather than universal time. "

I just looked in the table definition for all of the columns which contain datetime date types. I don't see GetUtcDate or GetDate() anywhere in the table definition. Where should these values be displayed?

|||If the data is not being set by a default property, look in the stored procedures for them.|||

Hi Hypercode,

Actually,the datetime value is saved as UTC format in system or database. When there's a request from a user, the server will translate the time into local time which depends on the server's location and response the user's request. So pls be sure that the settings of the timezone on your server is correct ( or just as you want).

If the problem still exists, you have to translate the time manually.Here's the UDF that you might be interested in looking into

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=28712

Hope it helps.

Thanks

|||

Thanks to you guys for pitchin in!

I still didn't get her straightened out yet. Been busy with other stuff (on the same project). I'll be getiing this straightened out though when I get a chance.

DateTime validation throgh sql query

hai friends,
how can i made validation of date time through sql query?

Swati

Check out the SQL Function: IsDate()|||Validation is best done from front end technology rather than make a round trip to the DB just to validate a date field.