日期:2014-05-17  浏览次数:20426 次

SQL 存储过程种 表变量操作缓慢

select convert(varchar(10),CreateTime,120) as t,COUNT(DISTINCT IMSI) AS c FROM [mobile].[dbo].[CheckUpdateLog]
where CreateTime>'2013-01-01 00:00:00' and CreateTime<'2013-01-30 23:59:59'
group by convert(varchar(10),CreateTime,120)
order by t

这段代码用时4秒 返回10行结果。


但是在下列代码时插入到一个表变量 会增加的12秒。
declare @ActiveUsersCount table (
t nchar(64),
c int
)
insert into @ActiveUsersCount(t,c)
select convert(varchar(10),CreateTime,120) as t,COUNT(DISTINCT IMSI) AS c FROM [mobile].[dbo].[CheckUpdateLog]
where CreateTime>'2013-01-01 00:00:00' and CreateTime<'2013-01-30 23:59:59'
group by convert(varchar(10),CreateTime,120)
order by t

insert into 一个表变量辉耀那么多时间么?
SQL

------解决方案--------------------

select convert(varchar(10),CreateTime,120) as t,COUNT(DISTINCT IMSI) AS c 
into #t --lz你使用临时表尝试一下。
FROM [mobile].[dbo].[CheckUpdateLog]
where CreateTime>'2013-01-01 00:00:00' and CreateTime<'2013-01-30 23:59:59'
group by convert(varchar(10),CreateTime,120)
order by t

------解决方案--------------------
具体原因不清楚,但是你的t是varchar而表变量是nchar,这两种数据类型的隐式转换肯定会有开销,你先试试把数据类型统一