[英]How to use stored procedure return value into an insert statement?
I have a stored procedure like 我有一个类似的存储过程
CREATE PROCEDURE GetSerial (@param1 int, @param2 int)
AS
BEGIN
-- do some insert/updates, so I can't use function
DECLARE @value AS int;
SET @value = 3;
return @value;
END
Now I declare a table variable 现在我声明一个表变量
DECLARE @Serials AS TABLE
(
ID int,
Value int
)
Now I wanna fill this table like 现在我想填这张桌子
INSERT INTO @Serials (ID, Value)
SELECT 1, GetSerial(1,2) -- *How can I call this?
So, can anyone help me how can i call the GetSerial stored procedure inside the SELECT statement to fill my table? 因此,有人可以帮助我如何在SELECT语句内调用GetSerial存储过程来填充我的表吗?
I recommend you avoid getting into this pattern/thinking, because stored procedures only return INTs, and those ints are really intended to describe how well the operation went, not a result/data from the operation. 我建议您避免进入这种模式/思维模式,因为存储过程仅返回INT,而这些int实际上是用来描述操作进行得如何的,而不是操作的结果/数据。 Example: 0 => failed, 1=> succeeded. 示例:0 =>失败,1 =>成功。 Not GetAgeInYears() => 29 不是GetAgeInYears()=> 29
https://docs.microsoft.com/en-us/sql/relational-databases/stored-procedures/return-data-from-a-stored-procedure?view=sql-server-2017 has a lot of info and concrete examples but in your specific case you'd need to execute the procedure and capture the result code into a variable then insert that: https://docs.microsoft.com/zh-cn/sql/relational-databases/stored-procedures/return-data-from-a-stored-procedure?view=sql-server-2017有很多信息和具体信息示例,但在您的特定情况下,您需要执行该过程并将结果代码捕获到变量中,然后将其插入:
DECLARE @ret INT;
EXEC @ret = GetSerial(1,2);
INSERT INTO @Serials VALUES(1, @ret);
Really you'd be better off using an output parameter or resultset if you have many values to return. 确实,如果要返回的值很多,最好使用输出参数或结果集。 See the above link for more 看到上面的链接了解更多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.