如何在Select语句中调用存储过程(SQL Server 2012)

时间:2017-10-02 17:45:41

标签: sql-server sql-server-2012

尝试运行下面的代码,它不起作用,我该如何解决?

SELECT Number_ID, EXEC dbo.UselessStoredProc @inputNum=Number_ID as ModifiedNumber
FROM [TestDb].[dbo].[Numbers]

存储过程看起来像这样,如果单独调用则有效:

CREATE PROCEDURE dbo.UselessStoredProc @inputNum int
AS
SELECT 'lol my number is: ' + CONVERT(varchar(max), @inputNum)
GO

--TEST
EXEC dbo.UselessStoredProc @inputNum=2;

我确实需要运行存储过程,而不是获取值。代码只是一个例子。

1 个答案:

答案 0 :(得分:1)

将您的程序转换为表值函数并使用cross apply()

create function NotAProc (@inputNum int) returns table as 
return 
select ModifiedNumber = 'lol my number is: ' + CONVERT(varchar(max), @inputNum);
go

select Number_ID, tvf.ModifiedNumber
from Numbers
  cross apply NotAProc(Number_ID) as tvf

rextester演示:http://rextester.com/HCJZQ54253

返回:

+-----------+---------------------+
| Number_ID |   ModifiedNumber    |
+-----------+---------------------+
|         0 | lol my number is: 0 |
|         1 | lol my number is: 1 |
|         2 | lol my number is: 2 |
|         3 | lol my number is: 3 |
|         4 | lol my number is: 4 |
|         5 | lol my number is: 5 |
|         6 | lol my number is: 6 |
|         7 | lol my number is: 7 |
|         8 | lol my number is: 8 |
|         9 | lol my number is: 9 |
+-----------+---------------------+

参考: