从 0001 开始在现有 table 中添加新列

Add new column in existing table starting from 0001

我在 sql 中有一个现有的 table 我需要的是一个列,它的值应该从 0001 开始,因此对于已经存在的值会增加。 Table姓名account_details

Account_num   name    new_column
1            vicky      0001
2            Sam       0002
5           James    0003
8           Abdul      0004

非常感谢您的帮助, 我正在使用 ms sql 服务器。 谢谢

我建议不要存储此派生信息。相反,您可以使用视图和 row_number():

create view myview as
select t.*, row_number() over(order by account_num) rn
from mytable t

这样可以节省您在添加或删除新行时使列保持最新的工作量。可以使用计算列来管理相同的功能。

0 填充可以用 format() 管理(将数字转换为字符串):

create view myview as
select t.*, format(row_number() over(order by account_num), '0000') rn
from mytable t

也就是说,如果您确实想要一个实际的列,那么您可以使用可更新的 cte:

alter table mytable add rn varchar(4);
with cte as (
    select rn, format(row_number() over(order by account_num), '0000') new_rn
    from mytable
)
update cte set rn = new_rn

考虑到,根据您的数据,这只是 Account_num 增加到 4 位数,计算列似乎最简单:

ALTER TABLE dbo.YourTable ADD New_Column AS RIGHT(CONCAT('0000',Account_num),4);

OP 更改了他们的数据,使我之前的回答无效。其他人对于现在的要求是正确的。无论如何都要离开这里。

使用row_number()

select t.*,
       right(concat('0000', row_number() over (order by account_num)), 4) as new_col
from table t;

对于现有列,您可以更改 table 架构:

alter table t
     add new_col as right(concat('0000', account_num), 4);

您还可以创建一个视图:

create view v1
   as select t.*,
             right(concat('0000', account_num), 4) as new_col
      from table t