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
4

3 回答 3

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
于 2012-05-31T16:20:29.730 回答
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
于 2012-05-31T16:20:41.960 回答
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
于 2012-06-01T07:27:19.353 回答