sql-server - 是否可以在 SQL Server 2008 中使用存储过程作为子查询?

标签 sql-server stored-procedures subquery

我有两个存储过程,其中一个返回付款列表,另一个返回这些付款的摘要(按货币分组)。现在,我有一个重复的查询:返回付款列表的存储过程的主查询是返回按货币的付款摘要的存储过程的子查询。我想通过将返回付款列表的存储过程作为返回货币付款摘要的存储过程的子查询来消除这种口是心非。这在 SQL Server 2008 中可能吗?

最佳答案

您最好将第一个过程转换为表值函数。如果涉及到多条语句,需要先定义返回表结构并填充。

示例:

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;

但是,如果是直接select(或者可以写成单个语句),那么可以使用INLINE tvf形式,这是高度优化的

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

第二个过程只是从第一个过程中进行选择

create proc getRecordsByStatus @t char(1)
as
select status, COUNT(*) CountRows from dbo.fn2_getRecords(@t)
group by status

以及你以前打电话的地方

EXEC firstProc @param

要获得结果,您现在可以从中选择

SELECT * FROM firstProc(@param)

关于sql-server - 是否可以在 SQL Server 2008 中使用存储过程作为子查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4889584/

相关文章:

mysql - 创建触发器: ERROR 1064 (42000): You have an error in your SQL syntax;

SQL - 获取更新值

Mysql 查询 - 操作数应包含 1 列

java - Sun JDBC ODBC 驱动程序或 MSSQL JDBC 驱动程序

sql - 禁止存储过程中的事务

sql-server - SET IDENTITY_INSERT xyz ON 的范围是什么?

python - 将 SQL 请求转换为 django

sql - Oracle SQL 相关更新

sql - 如何将所有包含用户、架构和角色的数据库从一台服务器移动/复制到另一台服务器

sql - SQL中的动态间隔创建