尝试创建一个函数,但我不知道它有什么问题。它在关键字“WITH”附近给出错误语法错误。
CREATE FUNCTION dbo.get_numseq (@max_rows AS BIGINT,@min_rows AS BIGINT) RETURNS TABLE
AS
-- returns up to 4,294,967,296 records
WITH
lv0 AS (SELECT 0 AS g UNION ALL SELECT 0),
lv1 AS (SELECT 0 AS g FROM lv0 AS a CROSS JOIN lv0 AS b),
lv2 AS (SELECT 0 AS g FROM lv1 AS a CROSS JOIN lv1 AS b),
lv3 AS (SELECT 0 AS g FROM lv2 AS a CROSS JOIN lv2 AS b),
lv4 AS (SELECT 0 AS g FROM lv3 AS a CROSS JOIN lv3 AS b),
lv5 AS (SELECT 0 AS g FROM lv4 AS a CROSS JOIN lv4 AS b),
Nums AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS n FROM lv5)
SELECT n FROM Nums where n >= @min_rows and n <= @max_rows ORDER BY n
GO
答案 0 :(得分:0)
您需要定义函数返回的表,并插入其中,而不是选择。
CREATE FUNCTION dbo.get_numseq (@max_rows AS BIGINT,@min_rows AS BIGINT)
RETURNS @t TABLE (n int)
AS
begin
-- returns up to 4,294,967,296 records
;WITH
lv0 AS (SELECT 0 AS g UNION ALL SELECT 0),
lv1 AS (SELECT 0 AS g FROM lv0 AS a CROSS JOIN lv0 AS b),
lv2 AS (SELECT 0 AS g FROM lv1 AS a CROSS JOIN lv1 AS b),
lv3 AS (SELECT 0 AS g FROM lv2 AS a CROSS JOIN lv2 AS b),
lv4 AS (SELECT 0 AS g FROM lv3 AS a CROSS JOIN lv3 AS b),
lv5 AS (SELECT 0 AS g FROM lv4 AS a CROSS JOIN lv4 AS b),
Nums AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS n FROM lv5)
insert @t
SELECT n FROM Nums where n >= @min_rows and n <= @max_rows ORDER BY n
return
end
请参阅http://technet.microsoft.com/en-us/library/ms191165(v=sql.105).aspx
答案 1 :(得分:0)
一些问题 - 你已经指定RETURNS TABLE
而没有定义所述表,插入它,缺少return语句等。
这是一个应该有用的副本:
CREATE FUNCTION dbo.Get_numseq
(
@max_rows AS BIGINT,
@min_rows AS BIGINT
)
RETURNS @t TABLE
(
N INT
)
AS
BEGIN
-- returns up to 4,294,967,296 records
WITH lv0
AS (SELECT 0 AS g
UNION ALL
SELECT 0),
lv1
AS (SELECT 0 AS g
FROM lv0 AS a
CROSS JOIN lv0 AS b),
lv2
AS (SELECT 0 AS g
FROM lv1 AS a
CROSS JOIN lv1 AS b),
lv3
AS (SELECT 0 AS g
FROM lv2 AS a
CROSS JOIN lv2 AS b),
lv4
AS (SELECT 0 AS g
FROM lv3 AS a
CROSS JOIN lv3 AS b),
lv5
AS (SELECT 0 AS g
FROM lv4 AS a
CROSS JOIN lv4 AS b),
Nums
AS (SELECT Row_number()
OVER (
ORDER BY (SELECT NULL)) AS n
FROM lv5)
INSERT INTO @t(n)
SELECT n
FROM Nums
WHERE n >= @min_rows
AND n <= @max_rows
ORDER BY n
RETURN
END