繁体   English   中英

如何在SQL中生成具有从0到最大值的序列号的表

[英]How to generate a table in SQL having sequence numbers from 0 to a max value

我目前正在使用

SET @startnum = 0;
SET @endnum = 10;

WITH n AS (
SELECT @startnum AS num
UNION ALL
SELECT @startnum +1 FROM n WHERE @startnum < @endnum
)
SELECT num FROM n ORDER BY num;

但是我使用的SQL版本不支持“ With table”查询。 另外,我不能按功能使用row_number()rank_over()分区。

如果需要这样的表,请执行以下操作:

create table t (int col1);
insert into t values (1);
create view v as select max(col1) as mcol1 from t;

然后根据需要进行以下操作:

insert into t
select col1 + mcol1
  from t, v
 where col1 + mcol1 <= NUMBEROFROWSDESIRED;

这将使每次执行的表倍增

我对SQLYog一无所知,但它看起来像MySQL工具,而不是SQL Server(此帖子标有T-SQL)。 我对MySQL也不了解太多,但是建议您创建一个具有所需数量的永久性数字表,然后就可以这样使用它:

-- say I need the numbers 1 to 10:
SELECT N
FROM tally
WHERE N BETWEEN 1 AND 10; -- these can be variables

要创建一个,可以使用以下语法(在T-SQL或MYSql中有效):

CREATE TABLE tally (N int NOT NULL,  PRIMARY KEY (N));

要填充它,您可以使用循环来实现(我不建议使用循环,但由于没有其他语法对您有用,因此这里会例外):

T-SQL版本:

DECLARE @i int;
SET @i = 1;

-- T-SQL syntax
WHILE @i <= 1000 -- change this to the max number of rows that you want
BEGIN
  INSERT dbo.tally VALUES (@i);
  SET @i = @i+1;
END;

MySQL语法:

-- MySQL syntax
declare ii int unsigned default 1000;
declare i  int unsigned default 0;

truncate table foo;
start transaction;
while i < ii do
  insert into dbo.tally (N) values (i);
  set i=i+1;
end while;
commit;

注意:我目前无法访问MySQL框,因此无法测试MySQL查询。

select (h*100+t*10+u+1) x from
(select 0 h union select 1 union select 2 union select 3 union select 4 union
select 5 union select 6 union select 7 union select 8 union select 9) A,
(select 0 t union select 1 union select 2 union select 3 union select 4 union
select 5 union select 6 union select 7 union select 8 union select 9) B,
(select 0 u union select 1 union select 2 union select 3 union select 4 union
select 5 union select 6 union select 7 union select 8 union select 9) C
order by x;

终于成功了! 看起来非常简单直接,我可以处理1000个数字。

如果有更好的出路,请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM