TSQL搜索日期范围

时间:2014-06-20 21:39:53

标签: sql-server tsql stored-procedures

我有一个搜索表单,允许您输入所需的任何信息并对该数据进行搜索。

以下是表单的内容:

enter image description here

我的目标是让他们输入开始和结束日期。但是,他们可以选择只输入一个或另一个。在这种情况下,我需要我的存储过程来正确处理它。

如果结束日期为空,则结束日期将成为今天的日期。如果开始日期为空,我们可以做任何日期(例如sqls默认日期,其中包括所有内容。

awardDate是正在搜索的字段。如果输入了两个日期,那么它必须是范围between start and end

以下是我当前的存储过程:

SELECT DISTINCT A.[awardID],
    A.[awardDescription],
    convert(varchar,cast(A.[awardValue] as money),1) as awardValue,
    CONVERT (VARCHAR (10), A.[awardDate], 101) AS awardDate,
    CONVERT (VARCHAR (10), A.[timestamp], 101) AS timestamp,
    B.[FirstName] + ' ' + B.[LastName] as empName,
    B.[ntid] AS empNTID,
    C.[awardType] as awardTypeName,
    D.[locationName],
    E.[awardStatusName]
FROM   taxTracker AS A
   INNER JOIN
   empTable AS B
   ON A.[employee] = B.[empID]
   INNER JOIN
   taxTrackerAwardTypes AS C
   ON A.[awardType] = C.[awardTypeID]
   INNER JOIN taxTrackerLocations as D
   ON A.[awardLocation] = D.[id]
   INNER JOIN taxTrackerStatuses as E
   ON A.[awardStatus] = E.[awardStatusID]
WHERE  ((A.[employee] IN (SELECT ParamValues.x2.value('empID[1]', 'VARCHAR(60)')
          FROM   @employees.nodes('/employees/employee') AS ParamValues(x2)))
    OR (ISNULL(@awardType, '') <> ''
        AND A.[awardType] LIKE '%' + @awardType + '%')
    OR (ISNULL(@awardStatus, '') <> ''
        AND A.[awardStatus] LIKE '%' + @awardStatus + '%'))
FOR    XML PATH ('details'), TYPE, ELEMENTS, ROOT ('root');

2 个答案:

答案 0 :(得分:1)

where (awarddate >= @startdate or @stardate is null)
and (awarddate <= isnull(@enddate, getdate())

答案 1 :(得分:0)

Awarddate between isnull (@startdate, '19000101') and isnull (@enddate, getdate ())