Sql-Server-2014

MS SQL Server 中的 UDF 返回以“with”開頭的查詢

  • January 19, 2021

這是一個完全有效的 SQL 查詢,並且可以很好地工作(例如)Microsoft SQL Server 2014

with t as (select 'a' as attr) select * from t

它返回a,當然可以簡化它並刪除with部分,但這不是重點,重點是找出一個說明需求/問題的最小範例。我可以將其中的一部分打包為 UDF:

CREATE PROCEDURE x(@__employee_id uniqueidentifier)
AS
RETURN (select 'a' as attr);

如何打包具有with塊的查詢?我的目標是實現以下目標:

CREATE PROCEDURE x (@__employee_id uniqueidentifier)
AS
RETURN (
   with t as (select 'a' as attr) select * from t
);

但是sql server不喜歡它,觸發錯誤:

Msg 156, Level 15, State 1, Procedure x, Line 4 [Batch Start Line 0]
Incorrect syntax near the keyword 'with'.
  1. 你正在混合程序和功能
  2. 對於 UDF,您的語法應該是

CREATE 或 alter function x (@__employee_id uniqueidentifier) 返回表 AS RETURN ( with t as (select ‘a’ as attr) select * from t );

按照如何從儲存過程返回表中的建議刪除return關鍵字:

CREATE PROCEDURE xx (@__employee_id uniqueidentifier)
AS
   with t as (select 'a' as attr) select * from t

引用自:https://dba.stackexchange.com/questions/283542