7

我有以下代码:

WITH OrderedOrders AS
(

SELECT *,  ROW_NUMBER() OVER (ORDER BY item) AS RowNumber
 from  dbo.fnSplit('1:2:3:5', ':')  
)

 select * from OrderedOrders where rownumber =2

我需要在函数中运行此代码,但是我无法使语法正确。现在是这样的:

CREATE FUNCTION [dbo].[FN_INDICE_SPLIT]
    (@sInputList VARCHAR(8000),@sDelimiter VARCHAR(8000),@INDICE INT)

RETURN TABLE 


;WITH OrderedOrders AS
( 
SELECT *,  ROW_NUMBER() OVER (ORDER BY item) AS RowNumber
 from  dbo.fnSplit(@sDelimiter, @INDICE)  
)
select ITEM from OrderedOrders where RowNumber=@INDICE

如果我尝试执行这个,它会给我这个错误:

Msg 156, Level 15, State 1, Procedure FN_INDICE_SPLIT, Line 4
Incorrect syntax near the keyword 'RETURN'.

我尝试以多种方式做到这一点,但我不断收到语法错误,我不知道出了什么问题。

4

2 回答 2

8

表值函数中的 WITH 之前不需要分号。特别是考虑到您甚至不能在 TVF 中使用多语句,因此没有理由存在语句分隔符。

正确的形式是CREATE FUNCTION (...) RETURNS TABLE AS RETURN <statement>

CREATE FUNCTION [dbo].[FN_INDICE_SPLIT]
    (@sInputList VARCHAR(8000),@sDelimiter VARCHAR(8000),@INDICE INT)
RETURNS TABLE 
AS RETURN
WITH OrderedOrders AS
( 
SELECT *,  ROW_NUMBER() OVER (ORDER BY item) AS RowNumber
 from  dbo.fnSplit(@sDelimiter, @INDICE)  
)
select ITEM from OrderedOrders where RowNumber=@INDICE
GO
于 2012-10-31T19:22:26.480 回答
1

您应该使用 RETURN* S *

RETURNS TABLE
于 2012-10-31T19:24:10.637 回答