使用存储过程的结果作为 SELECT 语句中的列
Use the result of Stored Procedure as column in SELECT statement
我有一个示例存储过程:
dbo.spSampleProcedure
@ID INT,
@Country VARCHAR(50)
此 SP 将 return 货币值(仅 1 列)。
现在我想这样实现:
SELECT
c.ID,
Amount = EXEC spSampleProcedure @ID = c.ID, @Country = c.Country
FROM Customer c
这可能吗?
您应该考虑 NOT 使用 sp_ 作为前缀命名您的存储过程。这是系统保留的前缀,可能会导致性能问题。您可以在 Aaron Bertrand 的 this article 上阅读更多相关信息。
为了执行您需要的操作,您可以首先创建一个用户定义的函数(如评论中所述),该函数将执行以下操作:
create function myfunc(@Id int, @Country varchar(50))
returns money
as
begin
declare @amount money
select @amount = amount
from Customer
where Id = @Id and Country = @Country
return @amount
end
只有这样你才能尝试你想做的事情:
select c.id,
amount = dbo.myfunc (c.id, c.country)
from customer c
我有一个示例存储过程:
dbo.spSampleProcedure
@ID INT,
@Country VARCHAR(50)
此 SP 将 return 货币值(仅 1 列)。
现在我想这样实现:
SELECT
c.ID,
Amount = EXEC spSampleProcedure @ID = c.ID, @Country = c.Country
FROM Customer c
这可能吗?
您应该考虑 NOT 使用 sp_ 作为前缀命名您的存储过程。这是系统保留的前缀,可能会导致性能问题。您可以在 Aaron Bertrand 的 this article 上阅读更多相关信息。
为了执行您需要的操作,您可以首先创建一个用户定义的函数(如评论中所述),该函数将执行以下操作:
create function myfunc(@Id int, @Country varchar(50))
returns money
as
begin
declare @amount money
select @amount = amount
from Customer
where Id = @Id and Country = @Country
return @amount
end
只有这样你才能尝试你想做的事情:
select c.id,
amount = dbo.myfunc (c.id, c.country)
from customer c