T-SQL - 仅在表中不存在时才在表中插入行

时间:2011-06-08 14:54:22

标签: sql-server tsql

我有如下所示的T-SQL。 @Results是一个表变量,'CTE'是一个公用表表达式。如果我要插入的SubId尚未插入表中,我只想在@Results表中插入行。下面显示的代码不起作用,我不知道为什么。有谁能看到这个问题?

Insert Into @Results (
    Cell, 
    CellSettings, 
    RecipeInstanceId, 
    BiasStartTime, 
    SubId 
    RuleInstanceId)
Select 
    Cell, 
    CellSettings, 
    RecipeInstanceId, 
    BiasStartTime, 
    SubId, 
    RuleInstanceId
From CTE
Where CTE.SubId NOT IN (Select SubId From @Results)

4 个答案:

答案 0 :(得分:6)

您需要先检查是否存在:

IF NOT EXISTS(SELECT * FROM @Results WHERE SubId = .......)
   INSERT INTO @Results (Cell, CellSettings, RecipeInstanceId, 
                          BiasStartTime, SubId, RuleInstanceId)
     SELECT 
         Cell, CellSettings, RecipeInstanceId, 
         BiasStartTime, SubId, RuleInstanceId
     FROM CTE

也许您可以将此要求(仅将那些尚不存在的行返回)放入CTE,这样您就不必再次从CTE过滤输出...

答案 1 :(得分:2)

我会这样做(假设 - 您的CTE中没有重复的SubID,即您插入X的SubID,然后在同一个查询中插入相同的SubID。)

WITH CTE AS
( 
  blah
), CTENEW AS
(
   SELECT CTE.* 
   FROM CTE
   LEFT JOIN @Results R ON CTE.SubID = R.SubID
   WHERE R.SubID IS NULL
)
Insert Into @Results (
    Cell, 
    CellSettings, 
    RecipeInstanceId, 
    BiasStartTime, 
    SubId 
    RuleInstanceId)
Select 
    Cell, 
    CellSettings, 
    RecipeInstanceId, 
    BiasStartTime, 
    SubId, 
    RuleInstanceId
From CTENEW

或者你可以将我在CTE中的连接滚动。

答案 2 :(得分:1)

尝试`except子句:

insert MyTable(c1, c2, c3)

select ot.c1, ot.c2, ot.c3
from OtherTable ot

except

select mt.c1, mt.c2, mt.c3
from MyTable

答案 3 :(得分:0)

使用“存在”

检查记录是否存在
If Not Exists(Select SubId From @Results)
    Insert Into @Results (
        Cell, 
        CellSettings, 
        RecipeInstanceId, 
        BiasStartTime, 
        SubId 
        RuleInstanceId)
    Select 
        Cell, 
        CellSettings, 
        RecipeInstanceId, 
        BiasStartTime, 
        SubId, 
        RuleInstanceId
    From CTE
    Where CTE.SubId NOT IN (Select SubId From @Results)