CREATE OR ALTER procedure SPD_NFS_PEDIDO (
    NFS_CONTROLE integer,
    CONTROLE integer)
as
declare variable PEDIDO_ITEM_PE_CONTROLE integer;
declare variable QUANTIDADE numeric(10,5);
declare variable T01 numeric(10,5);
declare variable T02 numeric(10,5);
declare variable T03 numeric(10,5);
declare variable T04 numeric(10,5);
declare variable T05 numeric(10,5);
declare variable T06 numeric(10,5);
declare variable T07 numeric(10,5);
declare variable T08 numeric(10,5);
declare variable T09 numeric(10,5);
declare variable T10 numeric(10,5);
declare variable T11 numeric(10,5);
declare variable T12 numeric(10,5);
declare variable T13 numeric(10,5);
declare variable T14 numeric(10,5);
declare variable T15 numeric(10,5);
declare variable T16 numeric(10,5);
declare variable T17 numeric(10,5);
declare variable T18 numeric(10,5);
declare variable T19 numeric(10,5);
declare variable T20 numeric(10,5);
declare variable CONFERENCIA_ID numeric(10,5);
BEGIN
SELECT A.PEDIDO_ITEM_PE_CONTROLE, A.QUANTIDADE,
A.T01,A.T02,A.T03,A.T04,A.T05,A.T06,A.T07,A.T08,A.T09,A.T10,
A.T11,A.T12,A.T13,A.T14,A.T15,A.T16,A.T17,A.T18,A.T19,A.T20,

COALESCE((SELECT FIRST 1 C.ID
        FROM TBCONFERENCIA_ITEM K, TBCONFERENCIA C
        WHERE K.CONFERENCIA_ID = C.ID
        AND C.TABELA = 'PED'
        AND C.TABELA_ID = A.PEDIDO
        AND C.STATUS = 4
        AND K.TABELA_ITEM_ID = A.PEDIDO_ITEM_PE_CONTROLE), 0) AS CONFERENCIA_ID

FROM TBNFS_ITEM A
WHERE
    A.PEDIDO_ITEM_PE_CONTROLE > 0
    AND A.PRODUTO_CODIGO > 0
    AND A.NFS_CONTROLE = :NFS_CONTROLE
    AND A.CONTROLE = :CONTROLE
INTO
:PEDIDO_ITEM_PE_CONTROLE, :QUANTIDADE,
:T01,:T02,:T03,:T04,:T05,:T06,:T07,:T08,:T09,:T10,:T11,:T12,:T13,:T14,
:T15,:T16,:T17,:T18,:T19,:T20, :CONFERENCIA_ID;

    IF (:PEDIDO_ITEM_PE_CONTROLE > 0) THEN
        BEGIN
           UPDATE TBPEDIDO_ITEM_SALDO SET
           QUANTIDADE = QUANTIDADE + :QUANTIDADE,
           T01 = T01+ :T01, T02 = T02+ :T02, T03 = T03+ :T03, T04 = T04+ :T04,
           T05 = T05+ :T05, T06 = T06+ :T06, T07 = T07+ :T07, T08 = T08+ :T08,
           T09 = T09+ :T09, T10 = T10+ :T10, T11 = T11+ :T11, T12 = T12+ :T12,
           T13 = T13+ :T13, T14 = T14+ :T14, T15 = T15+ :T15, T16 = T16+ :T16,
           T17 = T17+ :T17, T18 = T18+ :T18, T19 = T19+ :T19, T20 = T20+ :T20
           WHERE PEDIDO_ITEM_CONTROLE = :PEDIDO_ITEM_PE_CONTROLE;

           IF(:CONFERENCIA_ID > 0) THEN
           BEGIN
                UPDATE TBCONFERENCIA T SET T.STATUS = 2 WHERE T.ID = :CONFERENCIA_ID;
           END

        END

END