在函数内执行WITH语句

时间:2012-10-31 19:19:50

标签: sql-server tsql function

我有以下代码:

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'.

我试图在很多方面做到这一点,但我一直遇到语法错误,我不知道出了什么问题。

2 个答案:

答案 0 :(得分:8)

在TABLE-VALUED FUNCTION中,您不需要在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

答案 1 :(得分:1)

您应该使用RETURN * S *

RETURNS TABLE