Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common table expression (CTE) in table-valued function

I am used to using common table expressions (CTEs) with MSSQL 2008 R2. I know that the grammar is a bit fiddly about where they can appear, and that in ordinary T-SQL an explicit semicolon (or starting a new batch) is needed before a with expression. I would like to use CTEs in a user-defined function. For simple cases, this works:

create function dbo.udf_test()
returns table
with schemabinding
as
return (
  with foo as (
    select 5 as f
  )
  select f
  from foo
)

But now I would like to make my function udf_test a bit more elaborate. For example to declare a variable inside the body of the function. To start with I need to have explicit begin and end since the function body will no longer be a single statement. So I try to create one thus:

create function dbo.udf_test()
returns table
with schemabinding
as
begin
  return (
    with foo as (
      select 5 as f
    )
    select f
    from foo
  )
end

However this gives the error

Incorrect syntax near the keyword 'with'.

How can I use a CTE in my table-valued function if it is more complex than a single return statement?

like image 661
Ed Avis Avatar asked Oct 16 '25 07:10

Ed Avis


1 Answers

CREATE FUNCTION dbo.udf_test()
RETURNS 
@return TABLE 
(
    f int NOT NULL
)
AS
BEGIN

    WITH foo AS (
        SELECT 5 AS f
    )
    INSERT INTO @return
    SELECT f
    FROM foo;

    RETURN;
END
like image 124
Bruce Dunwiddie Avatar answered Oct 18 '25 02:10

Bruce Dunwiddie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!