INSERT VALUES WHERE NOT EXISTS

后端 未结 5 1493
我寻月下人不归
我寻月下人不归 2020-12-03 04:17

OK so I\'m trying to improve my asp data entry page to ensure that the entry going into my data table is unique.

So in this table I have SoftwareName and SoftwareTyp

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 05:17

    There is a great solution for this problem ,You can use the Merge Keyword of Sql

    Merge MyTargetTable hba
    USING (SELECT Id = 8, Name = 'Product Listing Message') temp 
    ON temp.Id = hba.Id
    WHEN NOT matched THEN 
    INSERT (Id, Name) VALUES (temp.Id, temp.Name);
    

    You can check this before following, below is the sample

    IF OBJECT_ID ('dbo.TargetTable') IS NOT NULL
        DROP TABLE dbo.TargetTable
    GO
    
    CREATE TABLE dbo.TargetTable
        (
        Id   INT NOT NULL,
        Name VARCHAR (255) NOT NULL,
        CONSTRAINT PK_TargetTable PRIMARY KEY (Id)
        )
    GO
    
    
    
    INSERT INTO dbo.TargetTable (Name)
    VALUES ('Unknown')
    GO
    
    INSERT INTO dbo.TargetTable (Name)
    VALUES ('Mapping')
    GO
    
    INSERT INTO dbo.TargetTable (Name)
    VALUES ('Update')
    GO
    
    INSERT INTO dbo.TargetTable (Name)
    VALUES ('Message')
    GO
    
    INSERT INTO dbo.TargetTable (Name)
    VALUES ('Switch')
    GO
    
    INSERT INTO dbo.TargetTable (Name)
    VALUES ('Unmatched')
    GO
    
    INSERT INTO dbo.TargetTable (Name)
    VALUES ('ProductMessage')
    GO
    
    
    Merge MyTargetTable hba
    USING (SELECT Id = 8, Name = 'Listing Message') temp 
    ON temp.Id = hba.Id
    WHEN NOT matched THEN 
    INSERT (Id, Name) VALUES (temp.Id, temp.Name);
    

提交回复
热议问题