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?

4

2 回答 2

2

一种选择是直接在合同表的 DDL 中执行此操作。这使用两列和一个计算列:

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),
    . . .
)
于 2012-04-30T13:44:18.190 回答
0

在插入时使用代替触发器。

甚至更好:在一个中心位置解决应用程序逻辑中的问题。

于 2012-04-30T13:05:45.790 回答