sqlserver date arithmetic problem - sql

I have a records of events with starttime and endtime for a calendar control.
I want to get the events done on a particular date say 2/28/2009
But the db table has date data in form 2/28/2009 10:00:00, 2/28/2009 12:00:00.
I tried this query in a sproc created in VS 2005 IDE but it didn't work
ALTER PROCEDURE dbo.spSelectBenchEvent
(
#EVENT_DATE DATE // BTW, THIS RETURNS ERROR :CANNOT FIND DATE DATATYPE.
//#EVENT_DATE HAS INVALID DATATYPE
)
AS
BEGIN TRAN
SET NOCOUNT ON;
SELECT ID, EID, BENCHID, PACCODE, START_TIME, END_TIME
FROM tbl_benchbook
WHERE START_TIME=EVENT_DATE
ORDER BY START_TIME
Thanks in advance.

There were many questions related to this one, check out:
Floor a date in SQL server
and for best performance-wise solution check: MS SQL Date Only Without Time
Basically your code could look like:
select
id, eid, benchid, paccode, start_time, end_time
from
tbl_benchbook
where start_time >= dateadd(dd, datediff(dd, 0, #event_date), 0)
and start_time < dateadd(dd, datediff(dd, 0, #event_date)+1, 0)

Based on your updated ques , this should work :
SELECT ID, EID, BENCHID, PACCODE, START_TIME, END_TIME
FROM tbl_benchbook
WHERE START_TIME >= #EVENT_DATE
AND START_TIME < DATEADD(day,1,#EVENT_DATE)
ORDER BY START_TIME

If you wish to evaluate all events on the date 3/29/2009 use the following where cluase.
SELECT *
FROM tableName
WHERE Date >= '2009/03/29' AND Date < '2009/03/30'
The key point to take away here is that in order to capture all records that occured on a given date you need to define a date range that includes all time values for that day.
Make sense?
Cheers, John

--1. you need to make sure there is no time on the parameter
--2. you can just use "+1" on the datetime, to get the next day
enter ALTER PROCEDURE dbo.spSelectBenchEvent
(
#EVENT_DATE DATETIME
)
AS
BEGIN TRAN
SET NOCOUNT ON;
--remove any time from given date
SET #EVENT_DATE=CONVERT(char(10),#EVENT_DATE,111)
SELECT ID, EID, BENCHID, PACCODE, START_TIME, END_TIME
FROM tbl_benchbook
WHERE START_TIME>=#EVENT_DATE AND START_TIME<#EVENT_DATE+1
ORDER BY START_TIME
code here

Related

Convert String column to Date in SSRS

I am trying to write a create statement for creating data source in SSRS. My Create Statement is as follows :-
Select TOP(cast(1000 as integer)) Name,
TName,
IName,
IType,
AvgPercent,
FCount,
PCount,
AvgInPages,
CONVERT(VARCHAR(10),RunDate,103) AS RunDate,
CONVERT(TIME(0), RunTime) AS RTime
from Index
where RunDateBetween #StartDate and #EndDate
Currently I have done it like this CONVERT(VARCHAR(10),RunDate,103) AS RDate, but between clause is not working. Between Clause only gives me record for start date and nothing after that. So I want to convert varchar to date I tried using this after searching on web CONVERT(Date,RunDate,103) AS RunDate but that gives me date as well as time whereas I just need date in that column. After lot of searching I am not able to find any concerete solution.Please help me.
How about this?
SELECT TOP 1000 NAME
,TName
,IName
,IType
,AvgPercent
,FCount
,PCount
,AvgInPages
,CAST(RunDate AS DATE) AS RDate
,CONVERT(TIME(0), RunTime) AS RTime
FROM INDEX
WHERE CAST(RunDate AS DATE) BETWEEN #StartDate
AND #EndDate

How to return only one instance of a command in SQL 2008r2

What I am attempted to do is only return the columns in the query below where the first dispatch time (inmain.firstdtm) and associated time stamp in the incident radio log match (incilog.timestamp) for the code representing a unit being dispatched('D').
The problem is the timestamp filed is logging to the nanosecond and the firstdtm field is not.
So in the where statement how can I get it to just compare the timedate fileds only to the second?
SELECT DISTINCT inmain.inci_id, inmain.calltime, inmain.firstdtm, incilog.timestamp, incilog.userid, inmain.secs2fn, inmain.secs2di,
inmain.calltaker, inmain.street
FROM incilog INNER JOIN
inmain ON incilog.inci_id = inmain.inci_id
WHERE (inmain.calltime>= dateadd(day,datediff(day,30,GETDATE()),0)
AND inmain.calltime< dateadd(day,datediff(day,0,GETDATE()),0)) AND (inmain.agency= 'UEMS')
AND (incilog.transtype='D') AND (inmain.firstdtm=???
If the incilog.timestampfield is a datetime/datetime2 for example you could remove the millisecond part by subtracting it using dateadd like this example:
declare #ts datetime
set #ts = getdate()
select #ts ts, dateadd(MILLISECOND, -datepart(MILLISECOND, #ts),#ts) ts_no_ms
ts ts_no_ms
----------------------- -----------------------
2014-11-14 01:47:42.663 2014-11-14 01:47:42.000
Using this logic you could do something like below in your where clause:
WHERE (inmain.firstdtm = dateadd(MILLISECOND, -datepart(MILLISECOND, incilog.timestamp),incilog.timestamp)

SQL Server: use parameter instead of GETDATE()

I have a stored procedure that uses selects like the following which works fine so far.
In this case for example it selects all records with a date from the previous month, i.e. March 2014 (column: dateEsc, formatted as nvarchar(20), example date: 2014-03-25).
My Select (example):
SELECT COUNT(*) AS groupCount
FROM Log_Esc
WHERE
CONVERT(DATE, dateEsc, 120) >= CONVERT(DATE, CONVERT(VARCHAR(6), DATEADD(month, -1, GETDATE()), 112) + '01', 112)
How do I have to change this if instead of the current Date (GETDATE()) I want to use a variable date input as the reference.
This input would be any date and is formatted as nvarchar(20) as well, example: 2014-04-03.
So instead of calculating the previous month compared to the current month from GETDATE() I would like to calculate the same from the variable date input.
Many thanks for any help with this, Tim.
First of all I think this query is better than the one you have:
SELECT COUNT(*) AS groupCount
FROM Log_Esc
WHERE DATE >= dateadd(month,datediff(month,0,dateadd(month,GETDATE(),-1)),0)
AND DATE < dateadd(month,datediff(month,0,GETDATE()),0)
If there is an index on the DATE field this can do a seek.
If you have a parameter #indate defined as date or datetime then this will work
SELECT COUNT(*) AS groupCount
FROM Log_Esc
WHERE DATE >= dateadd(month,datediff(month,0,dateadd(month,#indate,-1)),0)
AND DATE < dateadd(month,datediff(month,0,#indate),0)
See this question for more information on flooring a date to a month: Floor a date in SQL server
So what you want is a parameter:
Specifying Parameters in a Stored Procedure
Parameters allow you to pass user input to modify output.
An example
CREATE PROCEDURE dbo.Param1
#param int
AS
BEGIN
select 7 *#param as Value
END
EXEC dbo.Param1 5 -- 7 *5
EXEC dbo.Param1 -10 -- 7 * -10
Perhaps this'll give you some creative ideas for how you might implement parameters to accomplish your group count.

TSQL How can I update only the day part of a DATETIME column from a specific day

I would like to run a query on a number of incorrectly time-stamped rows (SQL 2005) and replace the DAY value only. My initial thought was just to use the REPLACE function as follows:
-- date correction
UPDATE mytable
SET [date] = REPLACE([date], '2014-02-20', '2014-02-27')
WHERE [date] LIKE '2014-02-20%'
..but that proved to be unsuccessful most likely because of the given column data-type. Any suggestions ?
You could also just make a DATEADD :
UPDATE mytable
SET [date] = DATEADD(DAY, 7, [date])
WHERE [date] >= '2014-02-20' AND [date] < '2014-02-21'

To get date from datetime in sql

I have datecreated field in a table. It contains value as "2009-12-30 11:47:20:297"
I have a query like this:
select *
from table
where DateCreated = getdate()
Although one row exists with today's date, I am not getting that row while executing above query. Can anybody help?
The reason why your query doesn't return the row you expect, is because GETDATE() returns the date and time portion at the moment the query was executed. The value in your DateCreated column will not match the time portion, so no rows are returned.
There are various ways to construct a query so that it evaluates the date based on only the date component. Here's one example:
WHERE YEAR(datecreated) = YEAR(GETDATE())
AND MONTH(datecreated) = MONTH(GETDATE())
AND DAY(datecreated) = DAY(GETDATE())
The unfortunate reality is that any query using a function on the column means that if an index exists on the column, it can't be used.
You can use something like this with Sql Server
CREATE FUNCTION [dbo].[udf_DateOnly](#DateTime DATETIME)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(dd,0, DATEDIFF(dd,0,#DateTime))
END
This line
DATEADD(dd,0, DATEDIFF(dd,0,#DateTime))
will strip out the Date portion.
The datetime field includes both the date and the time, accurate to the millisecond. Your query will only work if it is the exact millisecond stored in the database.
To check if it is today, but ignore the time of day, you can check for a range like this:
select * from table where
DateCreated >= '2009-12-30' and
DateCreated < '2009-12-31'
You can use that in conjunction with a function that converts the current date, as astander or Khilon has posted. Here is a full example using astander's answer. Also, as Craig Young points out, this will work with indexes.
select * from table where
DateCreated >= DATEDIFF(dd,0,GETDATE()) and
DateCreated < DATEDIFF(dd,0,GETDATE())
The simplest solution might be :
SELECT CAST(GETDATE() as DATE)
You can convert datetime to a string with only the date by using
CONVERT(varchar(8), GETDATE(), 112)
If needed, you can then change it back to datetime and as a result you'll get a datetime with the hours, minutes, seconds and milliseconds set to zero.