繁体   English   中英

SQL Server-日期,大于和小于

[英]SQL Server - Dates, Greater than and Less than

我有这个存储过程:

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子句有什么问题?

我觉得您的查询应该像下面这样写。 我认为你需要查询可在所有汽车startDatereturnDate ,需要基于Check 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 > startdatewhere子句中删除此行:

AND @startDate<=@returnDate

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

如果只希望用户将startdate设置为大于returndate的值,则可以在实际查询之前使用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 */

我需要从您的问题中了解您需要做的事情

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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