你可以帮我嵌套CTE吗?

时间:2015-03-14 00:02:22

标签: sql common-table-expression

你能帮我修改我的代码,我试着解释每一行

 WITH C ( ItemCode, LineNum, U_XAM_PED_SIG, U_XAM_ADU_SIG,
 U_XAM_FECHA_SIG, DocEntry ) AS  (  SELECT T0.ItemCode, T0.LineNum,
 t0.U_XAM_PED_SIG, T0.U_XAM_ADU_SIG, t0.U_XAM_FECHA_SIG, t0.DocEntry
        FROM INV1 T0 INNER JOIN OITM T1 ON T1.ItemCode = T0.ItemCode        WHERE
 T0.DocEntry = @list_of_cols_val_tab_del                AND T1.ManBtchNum='Y'
        AND T0.BaseEntry IS NULL ),   D AS  ( SELECT T0.BatchNum, T0.InDate,
 T0.Located, T0.Quantity            FROM OIBT T0 INNER JOIN IBT1 T1 ON
 (T0.BatchNum = T1.BatchNum AND T1.WhsCode = T0.WhsCode  )          WHERE
 T1.BaseType = 13           AND T0.ItemCode = T1.ItemCode                       AND
 T0.ItemCode = C.ItemCode   ------ I want to call previous CTE (error)      
            AND T1.BaseLinNum = 0 )     UPDATE C SET U_XAM_PED_SIG = 
 U_XAM_PED_SIG+LEFT(REPLACE (D.BatchNum,' ','')+'              ',12)+',
 ',             U_XAM_ADU_SIG = U_XAM_ADU_SIG+LEFT(D.Located+'                 
 ',19)+',',             U_XAM_FECHA_SIG =
 U_XAM_FECHA_SIG+LEFT(CONVERT(nvarchar(30), D.InDate, 20)+'         
 ',10)+','          WHERE DocEntry = @list_of_cols_val_tab_del          AND LineNum
 = c.LineNum
 --- basically I want to concatenate the different rows and update a single field

1 个答案:

答案 0 :(得分:1)

您无法通过CTE进行更新 - 或者即使您可以也不应该这样做。但是,看起来你根本不需要CTE。看看你是否可以生成如下所示的结果集:

select  I.U_XAM_PED_SIG, I.U_XAM_ADU_SIG, I.U_XAM_FECHA_SIG, -- Existing data
        D.BatchNum, D.Located, D.InDate -- New Data, or part of it
FROM    INV1 I
JOIN    OITM TM
    ON  TM.ItemCode = I.ItemCode
    AND TM.ManBtchNum = 'Y'
JOIN    OIBT BT
    ON  BT.ItemCode = I.ItemCode
JOIN    IBT1 T1
    ON  T1.ItemCode = I.ItemCode
    AND T1.WhsCode  = BT.WhsCode
    AND T1.BaseLinNum = 0
    AND T1.BaseType = 13
WHERE   I.DocEntry = @list_of_cols_val_tab_del
    AND I.BaseEntry IS NULL;

我不知道我对你的查询进行了解构的准确程度,因此请继续使用它。一旦获得现有数据以及将在一行中替换或附加到其中的新数据,您就可以构造update语句。

update语句的确切语法将取决于DBMS。关于最简单的SQL Server,您可以用select替换update/set

UPDATE  I
    SET I.U_XAM_PED_SIG = I.U_XAM_PED_SIG +f( D.BatchNum ),
        I.U_XAM_ADU_SIG = I.U_XAM_ADU_SIG + f( D.Located ),
        I.U_XAM_FECHA_SIG = I.U_XAM_FECHA_SIG + f( D.InDate )
FROM    INV1 I
etc.

但是写下查询,你就80%了。