如何在SQL Server的字符串列中生成连续数字

时间:2019-07-09 15:10:40

标签: sql sql-server tsql sql-server-2012

我必须在带有连续数字的特定字符串列的表中生成数据。

对于每个分支,我必须插入3个用户,并附加连续的数字(例如user1,user2,user3)。这里的挑战是我还必须生成附加有连续数字的分支字符串(例如branch001,branch002,branch003,直至branch700)

例如,下面是示例结构,

create table usersTable 
(
    id int identity(1,1),
    users nvarchar(100),
    branch nvarchar(100)
)

预期输出:

id    users    branch
-----------------------
1     user1    branch1
2     user2    branch1
3     user3    branch1
4     user4    branch2
5     user5    branch2
6     user6    branch2
......    
n     usern    branch700
n     usern    branch700
n     usern    branch700

有人可以建议在SQL Server中如何实现这一目标吗?预先感谢

2 个答案:

答案 0 :(得分:3)

更新

要获得所有分支机构越来越多的用户,请使用row_number()

INSERT INTO usersTable (users, branch)
SELECT CONCAT('User', ROW_NUMBER() OVER(ORDER BY t1.number, t0.number)), 
       CONCAT('branch', t1.number)
FROM tally t0
CROSS JOIN tally t1
WHERE t0.number <= 3
AND t1.number <= 700
ORDER BY t1.number, t0.number

原始版本

如果您已经有一个理货(数字)表,则使用insert...selectcross join的简单concat可以为您提供所需的数据:

INSERT INTO usersTable (users, branch)
SELECT CONCAT('User', t0.number), CONCAT('branch', t1.number)
FROM tally AS t0
CROSS JOIN tally AS t1
WHERE t0.number <= 3
AND t1.number <= 700

如果您还没有统计表,请阅读this SO post,了解创建统计表的方法。
您还可以阅读this database administrators post,了解您为什么真正想要一个。

如果您不能或不希望创建统计表,则可以使用公用表表达式动态生成统计表-有多种生成表的方式-戈登已经展示了递归CTE方法,因此我将展示另一种-使用row_numbercross join

With tally as
(
    SELECT TOP 700 ROW_NUMBER() OVER(ORDER BY @@SPID) As number
    FROM sys.objects a
    CROSS JOIN sys.objects b
)

INSERT INTO usersTable (users, branch)
SELECT CONCAT('User', t0.number), CONCAT('branch', t1.number)
FROM tally AS t0
CROSS JOIN tally AS t1
WHERE t0.number <= 3
AND t1.number <= 700

答案 1 :(得分:2)

这回答了问题的原始版本。

您可以使用递归CTE生成数据:

with u as (
      select v.users
      from (values ('user1'), ('user2'), ('user3')) v(users)
     ),
     n as (
      select 1 as n
      union all
      select n + 1
      from n
      where n < 700
     ) 
select u.users, concat('branch', n.n)
from u cross join
     n
order by n.n, u.users
option (maxrecursion 0);

insert如下所示:

with u as (
      select v.users
      from (values ('user1'), ('user2'), ('user3')) v(users)
     ),
     n as (
      select 1 as n
      union all
      select n + 1
      from n
      where n < 700
     ) 
insert into usersTable (users, branch) 
    select u.users, concat('branch', n.n)
    from u cross join
         n
    order by n.n, u.users
    option (maxrecursion 0);

Here是db <>小提琴。