存储过程返回多个结果集直接在MSSQL里合并

论坛中讨论过同一存储过程中多个 select 语句返回后结果集直接在 SQL 中合并的问题,未见到明确的解答,以前只知道可以通过客户端程序用nextRecord方法处理多个结果集,今天试了一下,对同一结构的查询,其多个结果集可以直接用 SQL 语句合并,程序如下:

create table t1(id int,col varchar(10))
insert into t1 select 1,'aaa'
insert into t1 select 2,'bbb'
create table t2(abc int,def varchar(10))
insert into t2 select 243,'fawed'
insert into t2 select 12344,'bbasdwaeb'
create table t3(faew int,faead varchar(10))
insert into t3 select 64523,'vasdf'
insert into t3 select 23,'fq34fd'
go
create procedure unionallrecord(
@sql1 nvarchar(max),
@sql2 nvarchar(max),
@sql3 nvarchar(max)
--如还有,继续
)as
begin
exec(@sql1)
exec(@sql2)
exec(@sql3)
--如还有,继续
end
go
create table #t(id int,col varchar(10))
insert into #t
exec unionallrecord 'select * from t1','select * from t2','select * from t3'

select * from #t
/*
id          col
----------- ----------
1           aaa
2           bbb
243         fawed
12344       bbasdwaeb
64523       vasdf
23          fq34fd

(6 行受影响)

*/
go
drop table t1,t2,t3,#t
drop procedure unionallrecord


向存储过程传递多条查询语句,可以这样直接获得全部结果集。

不过,如果几个查询的结果集数据结构不同,则这样处理会出错:

create table t1(id int,col varchar(10))
insert into t1 select 1,'aaa'
insert into t1 select 2,'bbb'
create table t2(abc int,def varchar(10),kkk int)
insert into t2 select 243,'fawed',1
insert into t2 select 12344,'bbasdwaeb',2
create table t3(faew int,faead varchar(10))
insert into t3 select 64523,'vasdf'
insert into t3 select 23,'fq34fd'
go
create procedure unionallrecord(
@sql1 nvarchar(max),
@sql2 nvarchar(max),
@sql3 nvarchar(max)
--如还有,继续
)as
begin
exec(@sql1)
exec(@sql2)
exec(@sql3)
--如还有,继续
end
go
create table #t(id int,col varchar(10))
insert into #t
exec unionallrecord 'select * from t1','select * from t2','select * from t3'

select * from #t
/*
消息 213,级别 16,状态 7,第 1 行
列名或所提供值的数目与表定义不匹配。
*/
go
drop table t1,t2,t3,#t
drop procedure unionallrecord


处理时要注意。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值