搜索 - 存储过程 - DateTime变量 - 简单分辨率?

时间:2014-10-30 13:53:02

标签: sql-server-2008 stored-procedures

我正在尝试创建一个存储过程,当输入三个变量时:

 @Bank_Number = 530 
 @Branch_Number = 002
 @Date_From = 10/28/2014
 @Date_To  = 10/29/2014 

它将返回与Date_FromDate_To匹配的Bank_NumberBranch_Number日期之间的所有记录。

我在这里的代码有点不正确我不知道如何继续。

Table I'm Querying in my stored procedure

ALTER PROCEDURE [dbo].[Something_Proc] 
      @Bank_Number varchar(3),
      @Branch_Number varchar(3),
      @Date_From datetime,
      @Date_To datetime
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @bankNumber varchar(3) = @Bank_Number,
            @branchNumber varchar(3) = @Branch_Number,
            @dateCreated datetime = @Date_From,
            @dateCreated datetime = @Date_To 

    SELECT DISTINCT     
            A.bankNumber, 
            A.branchNumber, 
            CONVERT(VARCHAR(8), A.dateCreated, 1)
    FROM        
        dbo.(table from picture) A
    WHERE
        (@bankNumber IS NULL OR Bank_Number LIKE @bankNumber + '%')
        AND (@branchNumber IS NULL OR Branch_Number LIKE @branchNumber + '%')
        AND (@dateCreated  IS NULL OR (MONTH(dateCreated) = MONTH(@dateCreated) 
                                       AND DAY(dateCreated) = DAY(@dateCreated)
                                       AND YEAR(dateCreated) = YEAR(@dateCreated)))
END

1 个答案:

答案 0 :(得分:0)

你不能使用这样的东西吗?

WHERE
    (@bankNumber IS NULL OR Bank_Number LIKE @bankNumber + '%')
    AND (@branchNumber IS NULL OR Branch_Number LIKE @branchNumber + '%')
    AND (@Date_From IS NULL OR @Date_From <= DateCreated)
    AND (@Date_To IS NULL OR DateCreated <= @DateTo)

基本上,您的@Date_From@Date_To参数都是NULL(那么参数不会以任何方式使用),或者如果它不为空,然后它用来比较DateCreated等于或大于@Date_From,等于或小于@Date_To ....