I have a table like:
Id PersonId Phone IsPrimary ----------------------------------- 1 1 12345 1 2 1 55555 0 3 2 66666 1 4 3 77777 1 5 3 88888 0 6 3 99999 0
How to create a restriction that allows you to insert only one IsPrimary = 1 per PersonId into this table. For all, there should be only one PersonId with IsPrimary = 1. So, as a result, I cannot insert the following record:
Id PersonId Phone IsPrimary ----------------------------------- 1 1 00000 1
You can try creating a unique filtered index:
CREATE UNIQUE INDEX UQ_Person_isPrimary ON Person (PersonId, IsPrimary) WHERE IsPrimary = 1
, . . ( IsPrimary) :
IsPrimary
Persons table ============= PersonId Name PrimaryPhoneId ----------------------------------- 1 Alice 1 2 Bob 3 3 Charlie 4 Phones table ============ Id PersonId Phone --------------------- 1 1 12345 2 1 55555 3 2 66666 4 3 77777 5 3 88888 6 3 99999
, . , - , . IsPrimary, ( 0, 1) , , , .
!
CREATE UNIQUE NONCLUSTERED INDEX uniquey_thingumyjig ON table_name (PersonId) WHERE IsPrimary = 1
https://msdn.microsoft.com/en-us/library/ms188783.aspx
Source: https://habr.com/ru/post/1661694/More articles:Keycloak Infinite Redirect - javascriptEvenly grouped items - xsltGet the primary key generated by a sequence using jdbctemplate / jdbc for Hana db - javaFfmpeg checks loaded stream - ffmpegXcode Firebase Crash Reporting Permission Denied - iosUnable to determine oracle data source on Wildfly 10 - oracleКак отключить Keep-Alive в IIS условно? - iisIs it possible to reduce notification time in Android? - androidJavascript Promise: Why is the caught exception still written as unmapped? - javascriptAuth0 with Rails API - ruby-on-railsAll Articles