创建 TVP 函数时必须声明 table 变量错误

Must declare the table variable error while creating a TVP function

我使用 TVP 创建了以下函数。我最初将数据插入 TVP,然后从中选择。

CREATE FUNCTION [dbo].employees_data(
  @employeeIds NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
-- WITH SCHEMABINDING
AS
BEGIN

  CREATE TYPE employees_data
  AS TABLE (can_view_all BIT,role_id INT ,employee_id INT);

  DECLARE @EmployeeDataTVP AS employees_data;

  INSERT INTO @EmployeeDataTVP (can_view_all, role_id, employee_id)
  SELECT
      ur.role_id,
      ua.employee_id
      INNER JOIN user_roles ur ON ur.user_account_id = ua.id
      WHERE ua.employee_id IN (SELECT * FROM STRING_SPLIT(@employeeIds, ','));


   RETURN (SELECT
    (
      CASE
      WHEN ed.role_id = 1 THEN (
        SELECT
          cc.id,
          ISNULL(cc.standard_name, cc.localized_name) AS name,
          cc.client_cost_center_id AS cost_center_id
        FROM s eccs
        LEFT JOIN centers cc on eccs.center_id = cc.id
        WHERE eccs.employee_id = ed.employee_id
        FOR JSON PATH
      )
      ELSE NULL
    END
    ) AS managed_places,
    ed.employee_id
  FROM @EmployeeDataTVP ed
   )
END

但是当我执行该函数时出现 Must declare the table variable \"@EmployeeDataTVP\". 错误。我不知道我做错了什么。

您不需要创建类型,而是 table 变量:

CREATE FUNCTION [dbo].employees_data(
  @employeeIds NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
-- WITH SCHEMABINDING
AS
BEGIN

  DECLARE @EmployeeDataTVP TABLE (can_view_all BIT,role_id INT ,employee_id INT);


  INSERT INTO @EmployeeDataTVP (can_view_all, role_id, employee_id)
  SELECT
      ur.role_id,
      ua.employee_id
      INNER JOIN user_roles ur ON ur.user_account_id = ua.id
      WHERE ua.employee_id IN (SELECT * FROM STRING_SPLIT(@employeeIds, ','));


   RETURN (SELECT
    (
      CASE
      WHEN ed.role_id = 1 THEN (
        SELECT
          cc.id,
          ISNULL(cc.standard_name, cc.localized_name) AS name,
          cc.client_cost_center_id AS cost_center_id
        FROM s eccs
        LEFT JOIN centers cc on eccs.center_id = cc.id
        WHERE eccs.employee_id = ed.employee_id
        FOR JSON PATH
      )
      ELSE NULL
    END
    ) AS managed_places,
    ed.employee_id
  FROM @EmployeeDataTVP ed
   )
END