将temptable列插入另一个表

时间:2017-07-27 05:55:41

标签: sql-server tsql cursor

TBMEMBER专栏

id,name,employeeno,userno,amount1,amount2,type,status

TBDEDUCT列

id,idno,employeeno,date,name,amount,status

TBITEMS

id,employeeno,userno,itemname,amount,status

SYNTAX

DECLARE memberlist CURSOR FOR SELECT id from TBMEMBER a where Status ='A' and Type = 'R' 
and employeeno not in (select EmployeeNo from TBRESIGN where  (txstatus='5' OR txstatus ='7' or txstatus='4') and EmployeeNo = a.EmployeeNo)

DECLARE @itemamt as decimal
select top 0 *
into #tempmember
from TBMEMBER

OPEN memberlist
    FETCH NEXT FROM memberlist
    INTO @id
    WHILE @@FETCH_STATUS = 0
    BEGIN

        INSERT INTO #tempmember SELECT * FROM TBMEMBER where id =@id
        select @itemamt =  sum(amount) from TBITEMS where employeeno = #tempmember.employeeno and status = '9'
        insert into #TBDEDUCT values (#tempmember.userno,#tempmember.EmployeeNo,getdate(),#tempmember.name,#tempmember.amount1,'P')
        insert into #TBDEDUCT values (#tempmember.userno,#tempmember.EmployeeNo,getdate(),#tempmember.name,#tempmember.amount2,'P')
        insert into #TBDEDUCT values (#tempmember.userno,#tempmember.EmployeeNo,getdate(),#tempmember.name,#tempmember.@itemamt,'P')
        DELETE FROM #tempmember
    END 

我试图从temptable中将值插入tbdeduct但是它给了我一个错误:

The multi-part identifier "#tempmember.SLAIdNo" could not be bound.

1 个答案:

答案 0 :(得分:1)

您需要为其他列声明变量,并在FETCH语句中为它们分配值。在INSERT语句中使用这些变量,而不是使用table.columname。但是,您不需要使用CURSOR。这是一种方式:

WITH CteTBMember AS( -- Rows from your CURSOR
    SELECT tm.* 
    FROM TBMEMBER tm
    WHERE 
        tm.Status ='A'
        AND tm.Type = 'R' 
        AND tm.employeeno NOT IN (
            SELECT EmployeeNo 
            FROM TBRESIGN 
            WHERE 
                (txstatus='5' OR txstatus ='7' or txstatus='4')
                AND EmployeeNo = a.EmployeeNo
        )
)
INSERT INTO #TBDEDUCT
SELECT
    tm.idNo,
    tm.EmployeeNo,
    GETDATE(),
    tm.name,
    x.amount,
    'P'
FROM CTeTbMember tm
CROSS APPLY( -- 3 types of amount to be inserted
    SELECT tm.amount1 UNION ALL

    SELECT tm.amount2 UNION ALL

    SELECT SUM(amount)
    FROM TBITEMS ti
    WHERE
        ti.employeeno = tm.employeeno
        AND ti.status = '9'
) x(amount);