存储过程未返回通过日期的任何数据

时间:2016-06-11 05:53:16

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

我有一个存储过程,它将一个参数作为DATE。这将从表中返回该日期的数据。

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

    SELECT * 
    INTO #temptable
    FROM
        (SELECT 
             a.CUser_id, b.User_Id, a.U_datetime AS REPORTDATE
         FROM 
             inward_doc_tracking_trl a 
         INNER JOIN 
             user_mst b ON a.CUser_id = b.mkey
                        AND a.U_datetime = @As_ONDATE) 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 U_datetime 
        FROM inward_doc_tracking_trl                        
        WHERE U_datetime = @As_ONDATE                     

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

        FETCH NEXT FROM Cur_1 INTO @CUser_id, @User_Id
    END

    CLOSE Cur_1
    DEALLOCATE Cur_1

    SELECT * FROM #temptable

    DROP TABLE #temptable                           
END

当我像这样执行存储过程时,我没有得到任何返回的行

exec UserReportData '20160610'

但在表中我确实有该日期的行。

喜欢在查询下方运行

SELECT U_datetime 
FROM inward_doc_tracking_trl    
WHERE u_datetime = '2016-06-10 14:56:11.000'

那么,为什么执行存储过程时没有返回记录?

1 个答案:

答案 0 :(得分:5)

因为您的u_datetime列包含日期&时间

一种方法是在WHERE子句中处理

and a.U_datetime >= @As_ONDATE
AND a.U_datetime <  DATEADD(DAY, 1, @As_ONDATE)

另外,您可能需要考虑将查询转换为不使用Cursor