将范围内的值插入 table
Insert values into table from a range
我正在尝试插入 table(比如 table1),我想在附加 char 或 int 声明后插入一系列数字?
例如。
范围 1-10
abc1,
abc2,
abc3,
abc4,
.
.
.
有什么想法吗?
为此我喜欢递归 CTE:
with nums as (
select @rangestart as n
union all
select n + 1
from nums
where n < @rangeend
)
insert into table1(col)
select 'abc' + cast(nums.n as varchar(255))
from nums;
如果您有超过 100 个号码,您应该使用 MAXRECURSION
选项。此外,任何数字 table 都可以达到相同的目的。
with nums as (
select 1 as n
union all
select n + 1 as n
from nums
where n <= 9
)
插入表 1(列)
select 'abc' + cast(nums.n as varchar(255))
来自 nums;
select * 来自表 1
Gordon Linoff 解决方案非常有效!只做了一个小的修改。
对于那些寻找未来解决方案的人。
DECLARE
@rangestart INT,
@rangeend INT
SET @rangestart = 1
SET @rangeend = 10
;
with nums as (
select @rangestart as n
union all
select n + 1
from nums
where n < @rangeend
)
insert into Table1(Colum)
select 'abc' + cast(nums.n as varchar(255))
from nums;
在我的测试table中,艺术家栏是我的测试table。
enter image description here
我比我更喜欢 Gordon 的回答,但它对我不起作用,因为 SQL 服务器只允许有限数量的递归(根据错误消息为 100 级)。
所以这是我使用 while() 循环的解决方案:
Declare @Current int = 1
Declare @End int = 20
Declare @Strings as table(Text varchar(5))
WHILE @Current <= @End
BEGIN
Insert Into @Strings Values('abc' + Cast(@Current as varchar(2)))
Set @Current = @Current + 1
END
Select * From @Strings
我正在尝试插入 table(比如 table1),我想在附加 char 或 int 声明后插入一系列数字?
例如。 范围 1-10
abc1,
abc2,
abc3,
abc4,
.
.
.
有什么想法吗?
为此我喜欢递归 CTE:
with nums as (
select @rangestart as n
union all
select n + 1
from nums
where n < @rangeend
)
insert into table1(col)
select 'abc' + cast(nums.n as varchar(255))
from nums;
如果您有超过 100 个号码,您应该使用 MAXRECURSION
选项。此外,任何数字 table 都可以达到相同的目的。
with nums as (
select 1 as n
union all
select n + 1 as n
from nums
where n <= 9
)
插入表 1(列) select 'abc' + cast(nums.n as varchar(255)) 来自 nums;
select * 来自表 1
Gordon Linoff 解决方案非常有效!只做了一个小的修改。 对于那些寻找未来解决方案的人。
DECLARE
@rangestart INT,
@rangeend INT
SET @rangestart = 1
SET @rangeend = 10
;
with nums as (
select @rangestart as n
union all
select n + 1
from nums
where n < @rangeend
)
insert into Table1(Colum)
select 'abc' + cast(nums.n as varchar(255))
from nums;
在我的测试table中,艺术家栏是我的测试table。 enter image description here
我比我更喜欢 Gordon 的回答,但它对我不起作用,因为 SQL 服务器只允许有限数量的递归(根据错误消息为 100 级)。
所以这是我使用 while() 循环的解决方案:
Declare @Current int = 1
Declare @End int = 20
Declare @Strings as table(Text varchar(5))
WHILE @Current <= @End
BEGIN
Insert Into @Strings Values('abc' + Cast(@Current as varchar(2)))
Set @Current = @Current + 1
END
Select * From @Strings