1

I have a table called SharedNumber, which has only one field - an integer number called LastNumber which can have one and only one entry.

There are about 40 or 50 odd completely separate Access databases that use this LastNumber entry as a common reference point. It is essentially being used to manually generate unique primary keys for a system that isn't able to generate them by itself. It is ugly and messy, and I am in the process of gradually weaning them off one by one, but in the interim I need to build a process in SQL Server which would reference this same entry.

I am dealing with the following:

1.

The shared number table:

create table SharedNumber
( 
    [LastNumber] int not null
) ON [PRIMARY]


Insert into SharedNumber
values
(234) --This is the most recent shared number

2.

An input data table (InputTable) that will continuously receive new entries, and for which new ContractID fields values need to be generated manually by incrementing LastNumber. For simplicty, let's say this table is uniquely defined on Name.

create table InputTable
(

    [ContractID] int NULL,
    [Name] varchar(50) not null
 ) ON [PRIMARY]


Insert into InputTable
values
(101,'ABC'),
(102,'DEF'),
(NULL,'GHI'),
(NULL,'JKL'),
(NULL,'MNO')

Entries 'GHI', 'JKL' and 'MNO' need ContractID values, so I want to incrementally create new numbers for them, based on LastNumber, and then update LastNumber to the last one that was generated. The eventual result I want is:

ContractID    Name
101           ABC
102           DEF
235           GHI
236           JKL
237           MNO


LastNumber
237

Anyone have any ideas on a good way to do this?

Karl
  • 5,573
  • 8
  • 50
  • 73

2 Answers2

2

One option would be to do this directly in the DDL for the contract table. This uses two columns and a computed column:

create table whatever (
    BuiltInContractId int identity(1000000,1) not null, -- the 1000000 is just to set a range for contract ids
    OverrideContractId int, -- what a user inputs,
    ContractId as coalesce(OverrideContractId, BuiltInContractId),
    . . .
)
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Use an instead-of trigger on insert.

Or even better: Solve the problem in the application logic in a central place.

usr
  • 168,620
  • 35
  • 240
  • 369