2016-11-23 32 views
0

我目前使用如何生成SQL表具有0序列号的最大值

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的版本。 此外,我无法使用row_number()rank_over()按功能分区。

+0

mySQL工作台6.2 2008版 – Dgstah

+0

当然!将更新.. – Dgstah

回答

0

如果我需要这样一个表格,我做到以下几点:

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; 

这将在每次执行

+0

这一步是有效的,但我将不得不手动执行查询,而numberofrowsdesired也是一个自动编号。有没有其他方法? – Dgstah

+0

你可以把它放在一个while循环中,用一个(shell)变量代替NUMBEROFROWSDESIRED并迭代直到插入的行数不是2的乘方。(0不是2的乘方,因此如果你需要例如16384行,你最终会得到额外的执行无所事事)。 – Ronald

0

我双倍的表对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的盒子。

0
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个号码。

如果有更好的方法,请让我知道。