如何在每个用户的游标中运行LOOP

时间:2016-06-11 12:02:30

标签: sql sql-server sql-server-2005

我有一个SP,它给了我两条记录(2个用户名),如下所示

SP loop

现在,

  

我想要的是使用cursor循环每个用户,并从表中显示其数据,该日期将在参数

中传递

以下是我的SP。

ALTER PROCEDURE GET_USER_REPORT_DATA
        @From_Date datetime,
        @To_Date datetime

    AS
    BEGIN

        Select * into #GetUserTable
            from
                (
                      select distinct a.N_UserMkey, b.mkey,   
                      b.first_name + ' ' + b.last_name NAME from inward_doc_tracking_trl a inner join user_mst b on 
                      a.N_UserMkey = b.mkey 
                      where a.U_datetime between @From_Date and @To_Date                  
                ) as xx     

    DECLARE @N_Usermkey int, @mkey int, @NAME varchar       
        DECLARE UserCursor CURSOR FOR  
            select distinct a.N_UserMkey, b.mkey,   
                      b.first_name + ' ' + b.last_name NAME from inward_doc_tracking_trl a inner join
                      user_mst b on a.N_UserMkey = b.mkey 
                      where a.U_datetime between @From_Date and @To_Date
        OPEN UserCursor

    FETCH NEXT FROM vendor_cursor   
            INTO @N_Usermkey, @mkey, @NAME 

        -- need to run loop for each user

            SELECT * FROM #GetUserTable
                         DROP TABLE #GetUserTable
    END

GO

我不知道如何使用cursor请让我知道

1 个答案:

答案 0 :(得分:2)

在你所有简单的选择查询中你都不需要光标就足够了......

select  a.N_UserMkey
       ,b.mkey
       ,ISNULL(b.first_name + ' ','') + ISNULL(b.last_name,'') NAME 
from inward_doc_tracking_trl a 
inner join user_mst b on a.N_UserMkey = b.mkey 
where a.U_datetime between @From_Date and @To_Date