有没有办法在另一列上定义标识列?我想要完成的是一个保存订单位置的表,这些订单可以随时放在那里。所以可能已经让我们在表格中说了三个位置,看起来有点像这样:
OrderNumber | OrderPosition
10001 1
10001 2
10001 3
现在我想在不计算OrderPosition列的正确值的情况下添加另一个位置。这是因为我想将多个订单的新头寸写入表中,并希望避免对各个订单进行游说。我更倾向于使用OrderPosition作为基于OrderNumber列重新接种的标识列的解决方案。因此,如果我为新订单添加订单头寸,它将从1开始,如果我为订单10001添加另一个仓位,则会继续4。
答案 0 :(得分:1)
编写一个基于OrderNumber返回MAX(OrderPosition)的标量函数。然后在order
的insert语句中引用该函数答案 1 :(得分:0)
您的要求不适用于标识列。
你需要创建自定义逻辑来获取普通列和基于组合的新no将生成..喜欢(读取注释,只选择一个逻辑)
declare @t table(OrderNumber int, OrderPosition int)
insert into @t values (10001, 1),(10001, 2),(10001, 3),(10001, 4)
select * from @t
--now insert new record with old orderno
declare @seq int = 1
declare @ordernumberNew int = 10001
--Eigher you can use :- insert to more understand
if( exists(select orderposition from @t where OrderNumber = @ordernumberNew ))
begin
set @seq = (select max(OrderPosition) + 1 from @t where OrderNumber = @ordernumberNew )
end
insert into @t values (@ordernumberNew , @seq )
select * from @t
--or another twist of above statement, insert directly as
insert into @t
values
(
@ordernumberNew,
case when exists (select orderposition from @t where OrderNumber = @ordernumberNew )
then (select max(OrderPosition) + 1 from @t where OrderNumber = @ordernumberNew )
else 1 end
)
select * from @t
--Now enter the not exist order no
set @ordernumberNew = 10006
insert into @t
values
(
@ordernumberNew,
case when exists (select orderposition from @t where OrderNumber = @ordernumberNew )
then (select max(OrderPosition) + 1 from @t where OrderNumber = @ordernumberNew )
else 1 end
)
select * from @t