将NOT EXISTS与INSERT ... SELECT结合使用

时间:2013-04-23 07:23:20

标签: sql-server

以下代码根据另一行中的值将新行插入表中,但它也允许重复数据。我想使用NOT EXISTS,以便如果已经有一行具有该值,那么它将不会插入另一行,但不确定如何集成它。

INSERT INTO [Grading].[dbo].[tblObservations]
       ([FormID]
       ,[Data]
       ,[UserID]
       ,[DateOfObservation]
       ,[Final]
       ,[ValidTo]
       ,[ID_Grading]
       ,[ID_ObservationKind]
       ,[Created]
       ,[Modified]
       ,[RowVersion])
SELECT [FormID]
  ,'0'
  ,[UserID]
  ,[DateOfObservation]
  ,[Final]
  ,[ValidTo]
  ,[ID_Grading]
  ,40
  ,[Created]
  ,[Modified]
  ,[RowVersion]
  FROM [Grading].[dbo].[tblObservations]
  WHERE [ID_ObservationKind] = 39 AND [Data] = 'No' AND [Final] = 1

任何帮助表示感谢。

3 个答案:

答案 0 :(得分:1)

你可以尝试

IF NOT EXISTS
    (
    SELECT 1
FROM [Grading].[dbo].[tblObservations]
WHERE [ID_ObservationKind] = 39 AND [Data] = 'No' AND [Final] = 1
    )

    BEGIN
        -- Insert script
    END

答案 1 :(得分:1)

试试这个 -

USE [Grading]

INSERT INTO [dbo].[tblObservations]
(
      FormID
    , Data
    , UserID
    , DateOfObservation
    , Final
    , ValidTo
    , ID_Grading
    , ID_ObservationKind
    , Created
    , Modified
    , [RowVersion]
)
SELECT 
      t.FormID
    , '0'
    , t.UserID
    , t.DateOfObservation
    , t.Final
    , t.ValidTo
    , t.ID_Grading
    , 40
    , t.Created
    , t.Modified
    , t.[RowVersion]
FROM dbo.tblObservations t
LEFT JOIN dbo.tblObservations t2 ON 
        t.FormID = t2.FormID
    AND t2.Data = '0'
    AND t.UserID = t2.UserID
    AND t.DateOfObservation = t2.DateOfObservation
    AND t.Final = t2.Final
    AND t.ValidTo = t2.ValidTo
    AND t.ID_Grading = t2.ID_Grading
    AND t2.ID_ObservationKind = 40
    AND t.Created = t2.Created
    AND t.Modified = t2.Modified
    AND t.[RowVersion] = t2.[RowVersion]
WHERE t.ID_ObservationKind = 39 
    AND t.Data = 'No' 
    AND t.Final = 1
    AND t2.FormID IS NULL

或试试这个 -

INSERT INTO [dbo].[tblObservations]
(
      FormID
    , Data
    , UserID
    , DateOfObservation
    , Final
    , ValidTo
    , ID_Grading
    , ID_ObservationKind
    , Created
    , Modified
    , [RowVersion]
)
SELECT 
      t.FormID
    , '0'
    , t.UserID
    , t.DateOfObservation
    , t.Final
    , t.ValidTo
    , t.ID_Grading
    , 40
    , t.Created
    , t.Modified
    , t.[RowVersion]
FROM dbo.tblObservations t
WHERE t.ID_ObservationKind = 39 
    AND t.Data = 'No' 
    AND t.Final = 1
    AND NOT EXISTS(
        SELECT 1 
        FROM dbo.tblObservations t2
        WHERE t2.ID_ObservationKind = 39 
            AND t2.Data = 'No' 
            AND t2.Final = 1
    )

答案 2 :(得分:0)

您正在寻找a "merge" or "upsert" in SQL。根据您的数据库,有很多方法可以执行此操作。如果您使用的是MySQL,则需要使用it's INSERT... ON DUPLICATE KEY UPDATE syntax.