简体   繁体   中英

SQL Stored Procedure to get Date and Time

I wish to create a stored procedure which can retrieve the datetime less than or greater than current sys date.. in my table,startdate and enddate has the value as 'datetime'

How do I get details between startdate and enddate in SQL stored procedure?

thanks in advance

Considering this table definition

CREATE TABLE [dbo].[Dates](
    [StartDate] [datetime] NOT NULL,
    [EndDate] [datetime] NOT NULL
) 

I assume that if you pass a date you want to know which rows satisfy the condition: startDate < date < EndDate. If this is the case you can use the query:

select * 
from Dates 
where convert(datetime, '20/12/2010', 103) between StartDate and EndDate;

A stored procedure could look like:

ALTER PROCEDURE [dbo].[GetDataWithinRange]
    @p_Date datetime
AS
BEGIN
    SELECT *
    from Dates 
    where @p_Date between StartDate and EndDate;
END

eg:

SELECT *
FROM MyTable
WHERE DATEDIFF ('d',mydatefield ,getdate() ) < 3

gets within 3 days

It sounds like you're trying to filter data in a table based on a date range. If this is the case (I'm having some trouble understanding your question), you'd do something like this:

select    *
from      MyTable m
where     m.Date between @DateFrom and @DateTo

Now, I'm assuming your filtering dates are put into the variables @DateFrom and @DateTo .

There are two things:

1> To get todays date we can write
SET @today_date = GETTDDT();  

2> To get Current time we can us ethe following query:

SET @today_time = (SELECT                                            
                digits(cast(hour(current time) as decimal(2,0)))||   
                digits(cast(minute(current time) as decimal(2,0)))|| 
                digits(cast(second(current time) as decimal(2,0)))   
              FROM sysibm/sysdummy1);   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM