如何使用函数简单地输出自然数?

时间:2016-12-22 07:39:07

标签: sql-server

输入数字为:(1,10)

输出数字是:
1
2
3
4
5
6
7
8
9
10个

3 个答案:

答案 0 :(得分:1)

您标记为MySQL& SQL-Serevr

答案几乎是SQL Server

FOR SQL-Server: -

也许有另一种方法可以实现这一目标。

我的方法是使用Table-Valued User-Defined Functions.

<强>演示: -

CREATE FUNCTION dbo.GetRanges(@start int, @end int)
RETURNS @MyTable TABLE 
(
    Numbers int
)
AS 
-- Returns the first name, last name, job title, and contact type for the specified contact.
BEGIN
    WHILE (@start <=@end)
    BEGIN
        insert into  @MyTable values (@start)
        SET @start = @start + 1
    END
    RETURN;
End
GO

现在执行下一个功能: -

Select * from dbo.GetRanges(1,10)

<强>结果: -

enter image description here

FOR MySQL: -

使用函数无法返回表格,此处为workaround,希望有所帮助。

另一种不使用While的方法。

通过使用ROW_NUMBER()作为下一个: -

SELECT numbers From
(
    select ROW_NUMBER()  OVER (ORDER BY so1.id) as numbers from sysobjects so1,sysobjects 
) a

where numbers between 1 and 10

答案 1 :(得分:1)

这将最多返回10 ^ 9个无处不在的数字并快速闪电

DECLARE @start INT = 1;
DECLARE @end INT = 10;
DECLARE @intervall INT=1;


WITH x AS(SELECT 1 AS N FROM(VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS tbl(N))--10^1
,N3 AS (SELECT 1 AS N FROM x CROSS JOIN x AS N2 CROSS JOIN x N3) --10^3
,Tally AS(SELECT TOP(@end-@start +1) (ROW_NUMBER() OVER(ORDER BY(SELECT NULL)))*@intervall + @start -1  AS Nr FROM N3 
          CROSS JOIN N3 N6 CROSS JOIN N3 AS N9)
SELECT *
FROM Tally

更新

内联表值函数相同,非常容易加入每个选择

CREATE FUNCTION dbo.RunningNumbers
(
 @start INT
,@end INT
,@intervall INT
)
RETURNS TABLE
AS
RETURN

WITH x AS(SELECT 1 AS N FROM(VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS tbl(N))--10^1
,N3 AS (SELECT 1 AS N FROM x CROSS JOIN x AS N2 CROSS JOIN x N3) --10^3
,Tally AS(SELECT TOP(@end-@start +1) (ROW_NUMBER() OVER(ORDER BY(SELECT NULL)))*@intervall + @start -1  AS Nr FROM N3 
          CROSS JOIN N3 N6 CROSS JOIN N3 AS N9)
SELECT *
FROM Tally
GO

SELECT * FROM dbo.RunningNumbers(1,10,1)

答案 2 :(得分:0)

尝试使用SQL Server

CREATE FUNCTION fuGetNumbers
(   
    @StartNumber INT NULL,
    @EndNumber INT NULL
)
RETURNS TABLE 
AS
RETURN 
(
    WITH nums AS (
                SELECT @StartNumber AS value UNION ALL SELECT value + 1 AS value FROM nums WHERE nums.value < @EndNumber
             )
    SELECT * FROM nums

)

你可以称之为

SELECT * FROM dbo.fuGetNumbers(1,10) OPTION (MAXRECURSION 0);