Search code examples
sqlsql-serverunique-index

Create a row which does not violate a unique index


I have a table with Id, AccountId, PeriodId, and Comment. I have a unique index for (AccountId, PeriodId). I want to create such a row which does not violate the unique index. AccountId and PeriodId cannot be null, they are foreign keys.

My only idea is to cross join the Account and Period table to get all valid combination and discard the already existing combinations and chose one from the rest?

Is it a good approach or is there a better way?

Update 1: Some of you wanted to know the reason. I need this functionality in a program which adds a new row to the current table and only allows the user to modify the row after it is already in the db. This program now uses a default constructor to create a new row with AccountId1 and PeriodId1, empty comment. If this combination is available then after insertion the user can change it and provide a meaningful comment (there can be at most one comment for each (AccountId, PeriodId). But if the combination is not available then the original insertion will fail. So my task is to give a combination to the program which is not used, so it can be safely inserted.


Solution

  • As it turns out my original idea is quick enough. This query returns an unused (AccountId, PeriodId).

    select top 1 * 
    from 
    (
        select Account.Id as AccountId, [Period].Id as PeriodId
        from Account cross join [Period]
    
        except
    
        select AccountId, PeriodId
        from AccountPeriodFilename
    ) as T