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 中使用存储过程作为子查询?
基础教程推荐
- Sql Server 字符串到日期的转换 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01