【问题标题】:passing only date as parameter in stored procedure to get results在存储过程中仅将日期作为参数传递以获取结果
【发布时间】:2015-09-16 09:24:57
【问题描述】:

我刚刚创建了以下存储过程

CREATE PROCEDURE [dbo].[FindIncomplete_Products]
     @type nvarchar(250),
     @category nvarchar(250),
     @country nvarchar(250),
     @subsidary nvarchar(250),
     @date datetime
AS
Begin  
    select  [dbo].[AB_Product].[ProductID],
            [dbo].[AB_Product].[ProductTitleEn],
            [dbo].[AB_Product].[ProductTitleAr], 
            [dbo].[AB_Product].[Status],
            [dbo].[AB_ProductType].[ProductTypeNameEn],
            [dbo].[AB_ProductType].[ProductTypeNameAr], 
            [dbo].[AB_ProductTypeCategory].[ProductCategoryNameEn],
            [dbo].[AB_ProductTypeCategory].[ProductCategoryNameAr],
            [dbo].[AB_Subsidary].[SubsidaryNameEn],
            [dbo].[AB_Subsidary].[SubsidaryNameAr],
            [dbo].[AB_Subsidary].[Country]
    from 
        [dbo].[AB_Product]
    inner join 
        [dbo].[AB_ProductType] on [dbo].[AB_ProductType].[ProductTypeID] = [dbo].[AB_Product].[ProductTypeID]
    inner join 
        [dbo].[AB_ProductTypeCategory] on [dbo].[AB_ProductTypeCategory].[ProductCategoryID] = [dbo].[AB_Product].[ProductCategoryID]
    inner join 
        [dbo].[AB_Subsidary] on [dbo].[AB_Subsidary].[SubsidaryID] = [dbo].[AB_Product].[Subsidary_ID]
    WHERE 
       (@type IS NULL OR [dbo].[AB_Product].[ProductTypeID]  LIKE '%' +  @type + '%')
       AND (@category IS NULL OR [dbo].[AB_Product].[ProductCategoryID] LIKE '%' +  @category + '%')
       AND (@country IS NULL OR [dbo].[AB_Subsidary].[Country] LIKE '%' +  @country + '%')
       AND (@subsidary IS NULL OR [dbo].[AB_Product].[Subsidary_ID] LIKE '%' +  @subsidary + '%')
       AND (@date IS NULL OR [dbo].[AB_Product].[CreatedDate] = @date)
End

我的数据库字段是日期时间字段,即[dbo].[AB_Product].[CreatedDate],当我访问此存储过程时,我以这种格式mm-dd-yyyy 传递了数据参数的值。

因为这是在寻找创建日期字段的确切值,即AND ([dbo].[AB_Product].[CreatedDate] = @date),所以我无法得到所有类似的结果。

例如,如果我想搜索创建日期为 2015-08-27 的所有产品,一旦我将其作为参数值传递,我无法获得创建日期为 2015-08-27 的所有结果,只有我可以获得创建日期的结果像这样2015-08-27 00:00:00.000。我错过了诸如创建日期值有2015-08-27 13:03:50.647

这样的结果

【问题讨论】:

  • 如果您使用过 sql server 2008 或更高版本,请在存储过程中使用 date 数据类型而不是 datetime 传递 @date 参数。

标签: sql-server date datetime stored-procedures


【解决方案1】:

使用DateDiff 函数而不是= 来比较日期。示例如下。

declare @str nvarchar(25)
set @str = '2015-09-17'
print datediff(d,getdate(),@str)

这个DateDiff 将返回两个日期之间的天数差。所以改变你的最后一行如下。

(@date IS NULL OR datediff(d,[dbo].[AB_Product].[CreatedDate],@date) = 0)

DateDiff 的工作原理如下。

DATEDIFF ( datepart , startdate , enddate )

您可以在herehere 阅读有关DateDiff ....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-24
    • 2021-09-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    相关资源
    最近更新 更多