无法执行存储过程

时间:2016-06-10 11:00:12

标签: sql datetime stored-procedures sql-server-2005

我有一张表,其中我的日期列值也随时间保存

像这样 2016-06-10 14:56:11.000

现在,在执行我的SP时,我将一个参数作为日期传递给exec UserReportData '06-10-2016',但它没有显示任何记录。因为它在表中有4条记录。

为什么?

更新

ALTER PROCEDURE [dbo].[UserReportData] 
    @As_ONDATE Datetime 
AS 
BEGIN 
    DECLARE @REPORTDATE datetime        
    DECLARE @OPENING INT        

    SELECT * 
    INTO #temptable
    FROM
        (SELECT DISTINCT
             a.CUser_id, b.User_Id,a.U_datetime as REPORTDATE, 
             b.first_name + ' ' + b.last_name AS USERNAME,
             0 OPENING, 0 TOTAL_DOCUMENT, 0 INWARD, 0 FIRST_LEVEL_PROCESSING, 0 DATA_ENTRY
         FROM 
             inward_doc_tracking_trl a, user_mst b
         WHERE
             a.CUser_id = b.mkey
             AND a.U_datetime = CONVERT(varchar(10), @As_ONDATE, 103)) AS x

    DECLARE Cur_1 CURSOR FOR 
        SELECT CUser_id, User_Id 
        FROM #temptable

    OPEN Cur_1

    DECLARE @CUser_id INT
    DECLARE @User_Id INT

    FETCH NEXT FROM Cur_1 INTO @CUser_id, @User_Id

    WHILE (@@FETCH_STATUS = 0)
    BEGIN
        SELECT @REPORTDATE  
        FROM inward_doc_tracking_trl                        
        WHERE U_datetime = CONVERT(varchar(10), @As_ONDATE, 103)

        UPDATE #temptable
        SET REPORTDATE = @REPORTDATE
        WHERE CUser_id = @CUser_id
          AND User_Id = @User_Id

        FETCH NEXT FROM Cur_1 INTO @CUser_id, @User_Id
    END

    CLOSE Cur_1
    DEALLOCATE Cur_1

    SELECT * 
    FROM #temptable

    DROP TABLE #temptable
END

1 个答案:

答案 0 :(得分:0)

您将日期作为字符串传递(隐式时间为00:00),您将其投射为日期,时间仍为00:00,并尝试将日期与时间匹配。由于时间不匹配,不会有任何结果。

您必须:

  1. 将日期时间投放到与确切日期匹配的日期(不好,需要重新计算列中的每个日期)
  2. 将搜索更改为日期+' 00:00'到目前为止' 23:59' (或者如果你快乐,你可以加一天)
  3. 更新您的where子句以采用简单选项2:

    where a.CUser_id = b.mkey
       and a.U_datetime BETWEEN CONVERT(varchar(10), @As_ONDATE, 103) 
                        AND DATEADD(day, 1, CONVERT(varchar(10), @As_ONDATE, 103))