如何将 table 变量从 FunctionA 传递到 Function,以及将 return table 变量从 Function 传递到 Function?

How to pass table variable from FunctionA to FunctionB, and return table variable from FunctionB to FunctionA?

如题,我写了一个简单的代码如下

functionA :将结果(table 变量)传递给函数 B

functionB : 将字段名称和 return 结果(table 变量)重新分配给 functionA

create function functionA(
    @Type nvarchar(max) 
    , @isArray bit = 0
)
returns @tempTable table (
    FieldId nvarchar(4000)
    , FieldName nvarchar(4000)
    , FieldType nvarchar(4000)
    , IsArray bit)
as
begin
    declare @tempTableA table (
        FieldId nvarchar(4000)
        , FieldName nvarchar(4000)
        , FieldType nvarchar(4000)
        , IsArray bit) 

    insert @tempTableA 
    select 
        *
    from 
        TableA
    where 
            @isArray = 1 and @Type='TypeA'
    
    insert @tempTable 
    select * from functionB(@tempTableA)

    return 

end
go
create function functionB(
    --How to get the table variable from functionA?
    @tempTableA table
)
returns @tempTableB table (
    FieldId nvarchar(4000)
    , FieldName nvarchar(4000)
    , FieldType nvarchar(4000)
    , IsArray bit)
as
begin
    insert @tempTableB
    select 
        FieldId [Id]
            , FieldName [Name]
            , FieldType [Type]
            , IsArray Array
    from 
        @tempTableA
    
    return 

end
go

当我期望函数 B 会收到错误消息时:

The syntax near the keyword 'table' is incorrect.

The data table variable "@tempTableB" must be declared.

The data table variable "@tempTableA" must be declared.

Table 变量应该是 READONLY。让我举个例子:

首先你应该创建用户定义 Table 类型:

CREATE TYPE [dbo].[tp_List] AS TABLE(
    [Val] [int] NULL
)
GO

然后在您的函数中使用 table 类型:

GO 
CREATE FUNCTION FunctionB( 
@TableName tp_List READONLY
)
RETURNS @mt table (a int)
AS
BEGIN
    INSERT INTO @mt
    SELECT * FROM @TableName
    RETURN
END
GO

和用法:

DECLARE @tbl tp_List
INSERT INTO @tbl
(
    Val
)
VALUES
(50)
SELECT * FROM FunctionB(@tbl)

输出:

a
50