N K N K - 6 months ago 16
SQL Question

Create cursor for temporary table in sql server 2005

I have some data inserted into the temporary table and I want to show COUNT in a LOOP by using

CURSOR


Here is the temp table:-

SELECT *
INTO #temp
FROM (
select distinct a.CUser_id, b.User_Id, b.first_name + ' ' + b.last_name NAME
from inward_doc_tracking_trl a, user_mst b
where a.CUser_id = b.mkey
and CStatus_flag = 1
and NStatus_flag = 4
) AS x
Select * from #temp order by NAME


[![TEMP TABLE data][1]][1]

I am new to cursor, kindly help

I am using
sql server 2005

Answer

As per our discussion in chat :

DECLARE @Count INT


SELECT * 
            INTO #temp
             FROM (
            select distinct a.CUser_id, b.User_Id, b.first_name + ' ' + b.last_name AS NAME, 0 AS RECEIVED 
            from inward_doc_tracking_trl a, user_mst b
            where a.CUser_id = b.mkey
            and CStatus_flag = 1
            and NStatus_flag = 4
            ) AS x


DECLARE Cur_1 CURSOR
    FOR SELECT CUser_id, User_Id FROM #temp


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 @Count = COUNT(*) FROM inward_doc_tracking_trl
        WHERE CUser_id = @CUser_id 
        AND NStatus_flag = 4 
        AND CStatus_flag = 1 
        AND a.U_datetime BETWEEN '01/04/2016' AND GETDATE()

        UPDATE #temp
        SET RECEIVED = @Count
        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 #temp
DROP TABLE #temp
Comments