How do I do this (business logic) on Sql Server? Restriction?

I want to add some type of business logic constraint to the table, but not sure how / where.

I have a table with the following fields.

  • IDENTIFICATION ID INTEGER
  • HubId INTEGER
  • CategoryId INTEGER
  • IsFeatured BIT
  • Foo NVARCHAR (200)

and etc.

So I want you to have only one great thing, for hubId + categoryId.

eg.
1, 1, 1, 1, 'blah'  -- Ok.
2, 1, 2, 1, 'more blah' -- Also Ok
3, 1, 1, 1, 'aaa' -- constraint error
4, 1, 1, 0, 'asdasdad' -- Ok.
5, 1, 1, 0, 'bbbb' -- Ok.

etc.

therefore the third row to be inserted will fail, because this studio AND category already has an excellent thing.

Is it possible?

+3
source share
1 answer

. - - :

:

  • IsFeatured = 1 HubId, CategoryId, IsFeatured
  • , SQL Server 2008 ( )

3,

PS: ID?

: UNIQUE CHECK

Edit:

,

CREATE UNIQUE INDEX IX_Foo ON Mytable (HubId, CategoryId) WHERE IsFeatured = 1

, (HubId, CategoryId) , IsFeatured = 1

+3

Source: https://habr.com/ru/post/1741721/


All Articles