SQL Server - 日期,大于和小于

时间:2015-08-10 12:58:18

标签: sql sql-server sql-server-2008

我有这个存储过程:

create procedure [dbo].[GetCarsByDates]
       (@startDate date, @returnDate date) 
as
    SELECT
        ManufacturerName, ModelName,
        CreationYear,
        Gear, CurrentKM,
        Picture,
        DATEDIFF(D, @startDate, @returnDate) * PricePerDay AS [Totalprice],
        PricePerDay, PricePerDayDelayed,
        InventoryCars.LicensePlate
    FROM 
        Models
    JOIN 
        Manufacturers ON Models.ManufacturerID = Manufacturers.ManufacturerID
    JOIN 
        InventoryCars ON InventoryCars.ModelID = Models.ModelID
    JOIN 
        CarsForRent ON CarsForRent.LicensePlate = InventoryCars.LicensePlate
    WHERE 
        CarsForRent.RentalStartDate < @startDate
        AND CarsForRent.RentalReturnDate < @returnDate
        AND CarsForRent.RentalReturnDate < @startDate
    ORDER BY 
        ManufacturerName, ModelName

我希望能够通过开始和返回日期选择属性。用户输入的开始日期必须大于返回日期,这正是我所做的,但它仍然无法正常工作。

问题在于我获得了不可用的项目的行结果。

我的where子句有什么问题?

3 个答案:

答案 0 :(得分:1)

我认为您的查询应该如下所示。 我假设您需要查询从startDatereturnDate的所有可用汽车,并且需要根据CarsForRent表格列进行检查 CarsForRent.RentalStartDateCarsForRent.RentalReturnDate

create procedure [dbo].[GetCarsByDates]@startDate date, @returnDate date
 as
BEGIN
    select DISTINCT ManufacturerName, ModelName, 
           CreationYear,Gear, CurrentKM, 
            Picture,
            DATEDIFF(D, @startDate, @returnDate)*PricePerDay as[Totalprice],
            PricePerDay,PricePerDayDelayed, InventoryCars.LicensePlate
     from Models 
         join Manufacturers  on Models.ManufacturerID=Manufacturers.ManufacturerID
         join InventoryCars  on InventoryCars.ModelID=Models.ModelID
         join CarsForRent    on CarsForRent.LicensePlate=InventoryCars.LicensePlate

 where 
   @startDate > CarsForRent.RentalReturnDate AND 
   CarsForRent.RentalReturnDate >CarsForRent.RentalStartDate 
   AND @startDate<=@returnDate
     order by ManufacturerName, ModelName  
 END

如果您不需要检查returndate是否&gt; startdatewhere子句中删除此行:

AND @startDate<=@returnDate

我创造了一个样本小提琴 请在左侧添加值并使用用例 http://sqlfiddle.com/#!6/00236/1

答案 1 :(得分:0)

如果您希望用户仅将startdate设置为大于returnsndate的值,则可以在实际查询之前使用IF块执行此操作。例如:

create procedure [dbo].[GetCarsByDates](@startDate date, @returnDate date) 
as
if @startDate <= @returnDate OR @startDate IS NULL OR @returnDate IS NULL
  BEGIN
   /* maybe do some stuff here */
   RAISERROR 'Errormessage', 11,1´;
   RETURN;
  END

/* here Comes your query without having to check the correctnes of the input-values */

答案 2 :(得分:0)

你需要做一些像我从你的问题中理解的那样的事情  

where 
(@startDate > @returnDate) and RentalReturnDate < @startDate