sql serve 中union all的问题

童登达 2013-09-04 11:38:06
这个问题我已经找了很久,但是没有找到满意答案,不找到csdn大神们能不能帮我解决。问题是这样的:我有一个存储过程,里面有几个查询,用union all连接,在sql server 2000中执行,单条都很快。但是用union all连起来,就变的非常缓慢。在sql server2008中执行,没有任何问题。请问大神们,这是什么原因呢?
...全文
206 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
KevinLiu 2013-09-04
  • 打赏
  • 举报
回复
首先2000和2008很难比,因为毕竟隔了一代的产品。你说的单条很快但是UNION ALL就慢了,那么你UNION ALL的时候结果集跟一条比如何?最好给出代码看一下
童登达 2013-09-04
  • 打赏
  • 举报
回复
引用 6 楼 mylife21 的回复:
union和union all不一样,数据集大的话排序耗时。
这里用union 和 union all 一样 都很慢,我2种都试了。还有在sql server 2000慢,大约5秒,在sql server 2008是正常的
mylife21 2013-09-04
  • 打赏
  • 举报
回复
union和union all不一样,数据集大的话排序耗时。
童登达 2013-09-04
  • 打赏
  • 举报
回复
引用 2 楼 row32hahaha 的回复:
贴代码,2008与2000很多机制都不同不能这样比,还是从代码入手优化下
存储过程是这样的,由于涉及到公司业务,把字段名称用略去了。麻烦你看一下
童登达 2013-09-04
  • 打赏
  • 举报
回复
引用 1 楼 SmithLiu328 的回复:
首先2000和2008很难比,因为毕竟隔了一代的产品。你说的单条很快但是UNION ALL就慢了,那么你UNION ALL的时候结果集跟一条比如何?最好给出代码看一下
存储过程是这样的,由于涉及到公司业务,把字段名称用略去了。麻烦你看一下
童登达 2013-09-04
  • 打赏
  • 举报
回复
ALTER proc [dbo].[存储过程]
(
参数	varchar(20),
参数 varchar(20),
参数	int
)
as
SET NOCOUNT ON

select * from (

  select 1 as 字段,'字段' as 字段,count(a.字段) as 字段
  from 表 a
  left join 表 b on a.字段 = b.字段
  left join 表 c on b.字段=c.字段 and c.字段=0
  left join 表 d on b.字段=d.字段 and d.字段=0
  where a.字段 like 'YF%' and b.字段=0  and (a.字段 is null or a.字段=2)  and isnull(b.字段,0)<>1
	and b.字段=1 and a.字段=b.字段
        and a.字段=参数 and a.字段=参数 
	and exists (select 1 from 视图 pw where 视图字段=参数 and 视图字段=c.字段 and (字段 is null or 字段=d.字段) and (字段 is null or 字段=b.字段))   

  union

select 1 as 字段,'字段' as 字段,count(a.字段) as 字段
  from 表 a
  left join 表 b on a.字段 = b.字段
  left join 表 c on b.字段=c.字段 and c.字段=0
  left join 表 d on b.字段=d.字段 and d.字段=0
  where a.字段 like 'YF%' and b.字段=0  and (a.字段 is null or a.字段=2)  and isnull(b.字段,0)<>1
	and b.字段=1 and a.字段=b.字段
        and a.字段=参数 and a.字段=参数 
	and exists (select 1 from 视图 pw where 视图字段=参数 and 视图字段=c.字段 and (字段 is null or 字段=d.字段) and (字段 is null or 字段=b.字段))   
  
  union

select 1 as 字段,'字段' as 字段,count(a.字段) as 字段
  from 表 a
  left join 表 b on a.字段 = b.字段
  left join 表 c on b.字段=c.字段 and c.字段=0
  left join 表 d on b.字段=d.字段 and d.字段=0
  where a.字段 like 'YF%' and b.字段=0  and (a.字段 is null or a.字段=2)  and isnull(b.字段,0)<>1
	and b.字段=1 and a.字段=b.字段
        and a.字段=参数 and a.字段=参数 
	and exists (select 1 from 视图 pw where 视图字段=参数 and 视图字段=c.字段 and (字段 is null or 字段=d.字段) and (字段 is null or 字段=b.字段))    

) c 
order by iid
row32hahaha 2013-09-04
  • 打赏
  • 举报
回复
贴代码,2008与2000很多机制都不同不能这样比,还是从代码入手优化下

34,874

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧