문제

I have a db with a table that has a rollover value such as OrderNumber and another column is year.

This is the primary key - a composite key - but there are other tables with which I need to use a foreign key relationship - I really would prefer to have an auto increment surrogate key for this table, the trick though is that OrderNumber and Year must be unique. IS there a good way to handle this?

I was reading here for some inspirations. Composite field in SQL Server, does it exist?

도움이 되었습니까?

해결책

As Vérace suggested, you can do both: create a surrogate (auto-increment) key to simplify joins and related table structures, and add a unique constraint on the two current PK columns to continue to enforce the proper data integrity.

In SQL Server, multiple columns can participate in a unique index / constraint:

ALTER TABLE dbo.Orders
ADD CONSTRAINT UQ_Year_OrderNumber
UNIQUE ([Year], OrderNumber);

Thus there is no need to create a computed column to combine the two columns.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 dba.stackexchange
scroll top