2012-05-31 77 views
1

如何從沒有主鍵的表中刪除滿足多個條件的行? (實際上主鍵是由每列形成)如何刪除這些條件?

這麼多的嘗試後我有先創建它插入行我要刪除,最後我嘗試刪除原來的表中的行的臨時表中的代碼符合臨時表的條件。

但它給我的錯誤有關無法連接的幾個部分標識符#temp.idCarga

也許是容易的,但我一直在努力了這麼多時間,我不能正確聚焦。

CREATE TABLE #TEMP 
(
    CC int, 
    idCarga int, 
    Tipo nvarchar(50), 
    Importe float, 
    Bloque nvarchar(50), 
    idsistema int 
) 

INSERT INTO #TEMP(CC,idCarga,Importe,Bloque,Tipo,IdSistema) 
select distinct CI.CC,CI.idCarga,CI.Importe,CI.Bloque,CI.Tipo,CI.idSistema 
from CONT_INGRESOS_InformeMayor CI 
INNER JOIN 
(
    SELECT idCarga,CC,Bloque,Importe,TIpo 
    FROM CONT_INGRESOS_InformeMayor 
) CI2 
    ON CI.CC = CI2.CC 
    AND CI.Bloque = CI2.Bloque 
    AND CI.TIpo <> CI2.Tipo 
WHERE CI.idCarga = @idCarga 
    AND CI2.idCarga = @idCarga 
    AND CI.Importe = 0 

DELETE 
FROM CONT_INGRESOS_InformeMayor 
WHERE idCarga = #temp.idCarga 
    AND tipo = #temp.tipo 
    AND importe = #temp.importe 
    and bloque = #temp.bloque 

回答

2

你錯過了你的DELETE聯接。試試這個:

DELETE _d 
FROM CONT_INGRESOS_InformeMayor AS _d 
INNER JOIN #temp AS _t 
    ON _d.idCarga = _t.idCarga 
    AND _d.tipo = _t.tipo 
    AND _d.importe = _t.importe 
    AND _d.bloque = _t.bloque 
1

DELETE是缺少JOIN#temp

DELETE t1 
FROM CONT_INGRESOS_InformeMayor t1 
INNER JOIN #temp t 
    ON t1.idCarga = t.idCarga 
     AND t1.tipo = t.tipo 
     AND t1.importe = t.importe 
     and t1.bloque = t.bloque 
1

在另一方面,你可以嘗試刪除行,而不涉及到一個臨時表:

DELETE FROM CI 
from CONT_INGRESOS_InformeMayor CI 
INNER JOIN 
(
    SELECT idCarga,CC,Bloque,Importe,TIpo 
    FROM CONT_INGRESOS_InformeMayor 
) CI2 
    ON CI.CC = CI2.CC 
    AND CI.Bloque = CI2.Bloque 
    AND CI.TIpo <> CI2.Tipo 
WHERE CI.idCarga = @idCarga 
    AND CI2.idCarga = @idCarga 
    AND CI.Importe = 0