How do I create a multiple column unique constraint in SQL Server

前端 未结 2 552
悲哀的现实
悲哀的现实 2021-02-04 01:10

I have a table that contains, for example, two fields that I want to make unique within the database. For example:

create table Subscriber (
    ID int not null         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-04 01:30

    I assume that only way to enter data into that table is through SPs, If that's the case you can implement some logic in your insert and update SPs to find if the values you are going to insert / update is already exists in that table or not.

    Something like this

    create proc spInsert
    (
        @DataSetId int,
        @Email nvarchar(100)
    )
    as
    begin
    
    if exists (select * from tabaleName where DataSetId = @DataSetId and Email = @Email)
        select -1 -- Duplicacy flag
    else
    begin
        -- insert logic here
        select 1 -- success flag
    end
    
    end
    GO
    
    
    create proc spUpdate
    (
       @ID int,
       @DataSetId int,
       @Email nvarchar(100)
    )
    as
    begin
    
    if exists 
    (select * from tabaleName where DataSetId = @DataSetId and Email = @Email and ID <> @ID)
        select -1 -- Duplicacy flag
    else
    begin
        -- insert logic here
        select 1 -- success flag
    end
    
    end
    GO
    

提交回复
热议问题