Is it possible to use a Stored Procedure as a subquery in SQL Server 2008?(是否可以在 SQL Server 2008 中使用存储过程作为子查询?)
问题描述
我有两个存储过程,其中一个返回付款列表,而另一个返回这些付款的摘要,按货币分组.现在,我有一个重复的查询:返回支付列表的存储过程的主查询是返回按货币支付的摘要的存储过程的子查询.我想通过使返回付款列表的存储过程成为返回按货币支付的摘要的存储过程的子查询来消除这种重复性.这在 SQL Server 2008 中是否可行?
I have two stored procedures, one of which returns a list of payments, while the other returns a summary of those payments, grouped by currency. Right now, I have a duplicated query: the main query of the stored procedure that returns the list of payments is a subquery of the stored procedure that returns the summary of payments by currency. I would like to eliminate this duplicity by making the stored procedure that returns the list of payments a subquery of the stored procedure that returns the summary of payments by currency. Is that possible in SQL Server 2008?
推荐答案
最好将第一个 proc 转换为 TABLE-VALUED 函数.如果涉及多条语句,需要先定义返回表结构并填充.
You are better off converting the first proc into a TABLE-VALUED function. If it involves multiple statements, you need to first define the return table structure and populate it.
示例:
CREATE proc getRecords @t char(1)
as
set nocouut on;
-- other statements --
-- final select
select * from master..spt_values where type = @t
GO
-- 变成--
CREATE FUNCTION fn_getRecords(@t char(1))
returns @output table(
name sysname,
number int,
type char(1),
low int,
high int,
status int) as
begin
-- other statements --
-- final select
insert @output
select * from master..spt_values where type = @t
return
end;
但是如果是直接选择(或者可以写成单条语句),那么可以使用高度优化的INLINE tvf形式
However, if it is a straight select (or can be written as a single statement), then you can use the INLINE tvf form, which is highly optimized
CREATE FUNCTION fn2_getRecords(@t char(1))
returns table as return
-- **NO** other statements; single statement table --
select * from master..spt_values where type = @t
第二个过程只是从第一个过程中选择
The second proc simply selects from the first proc
create proc getRecordsByStatus @t char(1)
as
select status, COUNT(*) CountRows from dbo.fn2_getRecords(@t)
group by status
还有你曾经打电话的地方
And where you used to call
EXEC firstProc @param
要获得结果,您现在可以从中选择
to get a result, you now select from it
SELECT * FROM firstProc(@param)
这篇关于是否可以在 SQL Server 2008 中使用存储过程作为子查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在 SQL Server 2008 中使用存储过程作为子查询?


- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01