日期:2014-05-18  浏览次数:20428 次

SQL语句优化问题?
以下参照TravyLee给出的SQL2008内幕方法,前面那个已经结贴,只好重开。原帖地址http://topic.csdn.net/u/20120327/15/d3a6f826-ce6c-4d48-ac5a-7bd9e1387aad.html?32111

这里想要说的是:下面这个方法能否优化?测试时,最终存入表tb0的数据是10万行,但是耗时40多分钟。。
if object_id('get_condays') is not null
  drop function get_condays
go
create function get_condays(@name varchar(10))
returns int
as
begin
 declare @maxcont int;
 with 
 d as
 (
  select logindate,(select min(b.logindate) from LoginTable b where b.logindate>=a.logindate and b.name=@name
  and not exists (select * from LoginTable c where c.logindate=dateadd(dd,1,b.logindate) and c.name=@name)) as grp
  from LoginTable a
  where a.name=@name
 ),
 e as
 (
  select min(logindate) as start_range,max(logindate) as end_range
  from d group by grp
 )
 select @maxcont=max(datediff(dd,start_range,end_range)+1) from e
return @maxcont
end
go
create clustered index clu_inx on LoginTable(name,logindate)
create table tb0(name varchar(10),maxcont int)
insert into tb0 select distinct name,dbo.get_condays(name) from logintable

望各位畅言!

------解决方案--------------------
不要使用多语句表值函数,杯具的一笔。
优化器不会考虑去优化函数里面的东东。。。
------解决方案--------------------
跟优化器没关系,

你的慢主要是这一句:

 and not exists (select * from LoginTable c where c.logindate=dateadd(dd,1,b.logindate) and c.name=@name)) as grp


不知道你为什么要这样写?
这样写的话每一行都会执行这个子查询,
而这个子查询又是查一个大表,
自然效率很低了