oracle增量表怎么写SQL,sql-使用唯一的增量值更新表中的int列

sql-使用唯一的增量值更新表中的int列

我正在尝试使用每行唯一的值填充其(SELECT ISNULL(MAX(interfaceID),0) + 1 FROM prices)列中缺少值的任何行。

我正在尝试执行以下查询:

UPDATE prices SET interfaceID = (SELECT ISNULL(MAX(interfaceID),0) + 1 FROM prices)

WHERE interfaceID IS null

我希望对每行评估(SELECT ISNULL(MAX(interfaceID),0) + 1 FROM prices),但是只执行一次,因此所有受影响的行都将获得相同的值,而不是不同的值。

可以在单个查询中完成吗?

7个解决方案

75 votes

declare @i int = SELECT ISNULL(MAX(interfaceID),0) + 1 FROM prices

update prices

set interfaceID = @i , @i = @i + 1

where interfaceID is null

应该做的工作

WKordos answered 2020-02-07T05:59:47Z

17 votes

DECLARE @IncrementValue int

SET @IncrementValue = 0

UPDATE Samples SET qty = @IncrementValue,@IncrementValue=@IncrementValue+1

ram nainar answered 2020-02-07T06:00:03Z

4 votes

简单的查询就是,只需将变量设置为所需的某个数字即可。然后通过从该数字增加1来更新所需的列。 对于所有行,它将通过递增1来更新每个行ID

SET @a = 50000835 ;

UPDATE `civicrm_contact` SET external_identifier = @a:=@a+1

WHERE external_identifier IS NULL;

Developer answered 2020-02-07T06:00:23Z

2 votes

在基于oracle的产品中,您可以使用以下语句:

update table set interfaceID=RowNum where condition;

HamedKhan answered 2020-02-07T06:00:43Z

2 votes

对于Postgres

ALTER TABLE table_name ADD field_name serial PRIMARY KEY

参考:[https://www.tutorialspoint.com/postgresql/postgresql_using_autoincrement.htm]

Nikhil Bhardwaj answered 2020-02-07T06:01:08Z

1 votes

尝试这样的事情:

with toupdate as (

select p.*,

(coalesce(max(interfaceid) over (), 0) +

row_number() over (order by (select NULL))

) as newInterfaceId

from prices

)

update p

set interfaceId = newInterfaceId

where interfaceId is NULL

这并不能使它们连续,但是可以分配新的更高ID。 要使它们连续,请尝试以下操作:

with toupdate as (

select p.*,

(coalesce(max(interfaceid) over (), 0) +

row_number() over (partition by interfaceId order by (select NULL))

) as newInterfaceId

from prices

)

update p

set interfaceId = newInterfaceId

where interfaceId is NULL

Gordon Linoff answered 2020-02-07T06:01:32Z

1 votes

假设您有此表的主键(应该有),并且使用CTE或WITH,则还可以使用带有自动联接到同一表的更新:

UPDATE a

SET a.interfaceId = b.sequence

FROM prices a

INNER JOIN

(

SELECT ROW_NUMBER() OVER ( ORDER BY b.priceId ) + ( SELECT MAX( interfaceId ) + 1 FROM prices ) AS sequence, b.priceId

FROM prices b

WHERE b.interfaceId IS NULL

) b ON b.priceId = a.priceId

我假设主键是价格ID。

派生表别名b用于通过ROW_NUMBER()函数以及主键列生成序列。 对于列interface-id为NULL的每一行,这将生成具有唯一序列值和主键值的行。

可以按其他顺序而不是主键对序列进行排序。

该序列通过子查询以当前MAX接口ID +1偏移。 MAX()函数将忽略NULL值。

WHERE子句将更新限制为那些为NULL的行。

然后将派生表连接到别名为a的同一表,并在主键列上进行连接,并将要更新的列设置为生成的序列。

Kevin Swann answered 2020-02-07T06:02:20Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值