论坛中讨论过同一存储过程中多个 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
处理时要注意。