Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute WITH statement inside a function

I have the following code:

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

I need to run this code inside a function, however I just can't make the syntax right. Here's how it is right now:

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

If I try to execute this, it gives me this error:

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

I've tried to do this in many ways, but I keep getting syntax errors and I don't know what's wrong.

like image 877
gabsferreira Avatar asked Oct 31 '12 19:10

gabsferreira


People also ask

Can I execute stored procedure inside function?

According to Microsoft standard, stored procedures cannot be executed inside the function, but technically it is possible with some tweaks.

Can we use CTE inside function?

CTE was introduced in SQL Server 2005, the common table expression (CTE) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. You can also use a CTE in a CREATE a view, as part of the view's SELECT query.

How do you execute a function?

For a user-defined function (UDF) to be executed with the EXECUTE FUNCTION statement, the following conditions must exist: The qualified function name or the function signature (the function name with its parameter list) must be unique within the name space or database. The function must exist in the current database.

Can you use a select statement in a function?

Select statements included within a function cannot return data to a client. FUNCTION SQL SERVER - Microsoft Q&A.


2 Answers

You don't need the semicolon before the WITH in a TABLE-VALUED FUNCTION. Especially considering that you cannot even have multi-statements in a TVF, there's no reason for a statement delimiter to be present.

The correct form is 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
like image 140
RichardTheKiwi Avatar answered Sep 25 '22 06:09

RichardTheKiwi


You should use RETURN*S*

RETURNS TABLE
like image 27
digscoop Avatar answered Sep 22 '22 06:09

digscoop