简体   繁体   中英

Creating a stored procedure in SQL Server 2014 that pulls between 2 dates

I'm a complete novice to SQL Server. I'm trying to create a stored procedure where you can search between two dates. I'd like my EXEC to read something like

EXEC Procedure TimeSheetIndexSearch (Date, Date)

(In which case, you'd input the dates before running EXEC.

CREATE PROCEDURE TimesheetIndexSearch
AS
   SELECT 
       Timesheets.Hours AS Hours, 
       Timesheets.DateWorked AS DateWorked, 
       Timesheets.Description AS Description,
       Timesheets.Id AS Id, 
       Users.Name AS UserName, 
       Projects.Name AS ProjectName
   FROM   
       Timesheets
   INNER JOIN 
       Users ON Timesheets.UserId = Users.Id
   INNER JOIN 
       Projects ON Timesheets.ProjectId = Projects.Id;

There's only one date column (no begindate or enddate). Do I use Where ? Or Order By ? Thanks!

Here you go:

CREATE PROCEDURE TimesheetIndexSearch (@Start DATETIME, @End DATETIME)
AS
SELECT Timesheets.Hours AS Hours
       , Timesheets.DateWorked AS DateWorked
       , Timesheets.Description AS Description
       , Timesheets.Id AS Id
       , Users.Name AS UserName
       , Projects.Name AS ProjectName
FROM   Timesheets
       INNER JOIN Users ON Timesheets.UserId = Users.Id
       INNER JOIN Projects ON Timesheets.ProjectId = Projects.Id
WHERE  Timesheets.DateWorked >= @Start
       AND Timesheets.DateWorked <= @End;

You can also use the keyword between as follows:

WHERE Timesheets.DateWorked BETWEEN @Start AND @End

Just be careful with between , as it is inclusive of the dates in the variables, the first approach is cleaner, and easier to read by all.

To run the proc you'd use

EXEC TimesheetIndexSearch '2015-01-01','2015-01-10'

Don't create a stored procedure for this. Create a stored function. This is much more versatile because you can use it in the from clause of a select :

CREATE FRUN TimesheetIndexSearch (
    @Start date,
    @End date
)
RETURNS table
AS
    RETURN (SELECT ts.Hours AS Hours, ts.DateWorked AS DateWorked,              
                   ts.Description AS Description,
                   ts.Id AS Id, u.Name AS UserName, p.Name AS ProjectName
            FROM Timesheets ts INNER JOIN
                 Users u
                 ON ts.UserId = u.Id INNER JOIN
                 Projects p
                 ON ts.ProjectId = p.Id
            WHERE ts.DateWorked >= @Start AND ts.DateWorked <= @End
           );

You can then use this as:

select f.*
from dbo.frun('2015-01-01', '2015-02-01');

Also, note how the use of table aliases makes the query easier to write and to read.

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