简体   繁体   English

将声明表变量传递给另一个存储过程

[英]Pass declare table variable to another stored procedure

I am sure the answer is NO , but I'll ask the expert anyway ;) 我确定答案是否定的 ,但是我还是会问专家;)

I've declared a table variable in my stored procedure. 我在存储过程中声明了一个表变量。

DECLARE @OrderMapIds TABLE
(
    OrderId INT NOT NULL,
    NewOrderId INT NOT NULL
);
INSERT INTO @OrderMapIds (OrderId, NewOrderId)
SELECT [OrderId], [OrderId] FROM [tblOrder]
...
...
...
EXEC [AS.uspOrder_MoveOrder] @OrderMapIds = @OrderMapIds;  --I need to move order ids based on the mapped id

I need to pass @OrderMapIds to [AS.uspOrder_MoveOrder] . 我需要将@OrderMapIds传递给[AS.uspOrder_MoveOrder] The question is how? 问题是如何?

CREATE PROCEDURE [AS.uspOrderItem_CopyRecord]
(
    @OrderMapIds AS TABLE -- This thrown error
)
AS
BEGIN
    ...
    ...
    ...
END;

Now, I can accomplish this problem using Table-Valued Parameter ( TVP ) . 现在,我可以使用表值参数( TVP )来解决此问题 But if I could pass it without TVP, then it will be better (so I don't have to create TVP for small stuff). 但是,如果我不用TVP就可以通过它,那会更好(所以我不必为小东西创建TVP)。

Now, after looking at Google, I am sure the answer is NO (ie. I need to create TVP to accomplish task above). 现在,在查看Google之后,我确定答案是否定的 (即,我需要创建TVP来完成上述任务)。 But I thought to ask the question in hope I might have missed something. 但是我想问这个问题,希望我可能错过了一些东西。

Any help is greatly appreciated. 任何帮助是极大的赞赏。

Thanks 谢谢

You are correct. 你是对的。 The answer is indeed No. 答案的确是没有。

In SQL Server, the only way to pass a table to a stored procedure is using a user defined table type. 在SQL Server中,将表传递给存储过程的唯一方法是使用用户定义的表类型。

You do have some confusion in the terms, though. 不过,您在术语方面确实有些困惑。
TVP is the parameter itself - so even if you could just pass any table variable a stored procedure - it would still be a Table Valued Parameter . TVP本身就是参数-因此,即使您可以将任何表变量传递给存储过程,它也仍然是表值参数

What you want to avoid (but can't) is a User Defined Table Type . 您要避免(但不能避免)的是用户定义的表类型

If this was allowed, you would end up with a stored procedure that takes in a table valued parameter with an unknown structure - And this could lead to errors, extremely cumbersome code, and worst of all - silently using the wrong data. 如果允许这样做,您将最终得到一个存储过程,该存储过程将采用具有未知结构的表值参数-这可能会导致错误,极其繁琐的代码,甚至更糟糕的是-静默地使用错误的数据。

An interesting alternative, especially when the table structure is variable/dependent will be to convert data as JSON/XML ( data type for parameter will be NVARCHAR). 一个有趣的替代方法,尤其是当表结构是可变/相关的时,将数据转换为JSON / XML(参数的数据类型为NVARCHAR)。

Way to go in your example will be 在您的示例中进行的方式是

DECLARE @OrderMapIds NVARCHAR(MAX)=
(
    SELECT [OrderId], [OrderId] FROM [tblOrder] FOR JSON PATH

);
...
...
...
EXEC [AS.uspOrder_MoveOrder] @OrderMapIds = @OrderMapIds; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM