简单合并删除失败

时间:2016-08-11 16:15:44

标签: sql sql-server sql-server-2008

FirstTable

ColumnOne | TabletwoCol | TablethreeColumn |
 1        |  2          |   5              |
 2        |  3          |   6              |
 3        |  8          |   10             |       

SecondeTable (TableTwo)   

TabletwoCol | Coln |
2           | ABC  |
3           | lmn  |
8           |  as  |
 1515       | addd |   

我想通过引用Tabletwocol来使用合并删除从我的借调表中删除 即来自 下面的行后面的SecondeTable(TableTwo)应该被删除

  2           | ABC  |
    3           | lmn  |
    8           |  as  |

应该被删除

我写过

 MERGE SecondeTable  PB USING  
             (SELECT DD.TabletwoCol  FROM   FirstTable DD) temptable
                              ON PB.TabletwoCol  =temptable.TabletwoCol 
                                WHEN MATCHED THEN
                                DELETE; 

我不知道什么事情没有发生

2 个答案:

答案 0 :(得分:0)

我不知道为什么它不起作用。它对我来说很好看。 也许你应该尝试使用DELETE

DELETE PB
FROM SecondeTable AS PB
INNER JOIN FirstTable DD
  ON PB.TabletwoCol  = DD.TabletwoCol;

答案 1 :(得分:0)

如果我理解正确,如果FirstTable中存在匹配项,则尝试从SecondTable中删除。试试这个

--DROP TABLE #FirstTable;
--DROP TABLE #SecondTable;
CREATE TABLE #FirstTable
    (
      ColumnOne INT
    , TabletwoCol INT
    , TablethreeColumn INT
    );

INSERT  INTO #FirstTable
        ( ColumnOne
        , TabletwoCol
        , TablethreeColumn
        )
VALUES  ( 1  -- ColumnOne - int
        , 2  -- TabletwoCol - int
        , 5  -- TablethreeColumn - int
        );
CREATE TABLE #SecondTable
    (
      TabletwoCol INT
    , Coln CHAR(5)
    );
INSERT  INTO #SecondTable
        ( TabletwoCol, Coln )
VALUES  ( 2  -- TabletwoCol - int
          , 'ABC'  -- Coln - char(5)
          ),
        ( 3  -- TabletwoCol - int
          , 'def'  -- Coln - char(5)
          );
SELECT  *
FROM    #FirstTable;

SELECT  *
FROM    #SecondTable;

MERGE #SecondTable AS Tgt
USING
    ( SELECT    TabletwoCol
      FROM      #FirstTable
    ) AS Src
ON Src.TabletwoCol = Tgt.TabletwoCol
WHEN MATCHED THEN
    DELETE;

SELECT  *
FROM    #FirstTable;
SELECT  *
FROM    #SecondTable;