加了个hint,为何结果不一样,求解释.
create table ap(id int not null, yx varchar(30) constraint pk_ap primary key (id))insert into apselect 1,'aaa' union allselect 2,'bbb' union allselect 3,'ccc' union allselect 4,'ddd' union allselect 5,'eee'select * from apid yx----------- ------------------------------1 aaa2 bbb3 ccc4 ddd5 eeedeclare @r1 varchar(50),@r2 varchar(50)select @r1='',@r2=''select @r1=@r1+yx+',' from ap where id>=3order by case when yx='yyy' then '1' else yx endselect @r2=''select @r2=@r2+yx+',' from ap where id>=3order by case when yx='yyy' then '1' else yx endoption(force order)select @r1 r1, @r2 r2r1 r2-------------------------------------------------- --------------------------------------------------ccc,ddd,eee, eee,(1 row(s) affected)
declare @r1 varchar(50),@r2 varchar(50)select @r1='',@r2=''select @r1=@r1+yx+',' from ap where id>=3order by 1,--yx --case when yx='yyy' then '1' else yx endselect @r2=''select @r2=@r2+yx+',' from ap where id>=3order by 1,--yx --case when yx='yyy' then '1' else yx endoption(force order)select @r1 r1, @r2 r2
[解决办法]
option (force order)
FORCE ORDER
指定在查询优化过程中保持由查询语法指示的联接顺序。
http://msdn.microsoft.com/zh-cn/library/ms181714%28v=SQL.90%29.aspx
[解决办法]
看了下执行计划,第2个语句比第1个语句少了一次“计算标量”,难道问题就处在这里?
[解决办法]
经测试,这个不是option(force order)造成的。以下两段的结果是一样的。
declare @r1 varchar(50),@r2 varchar(50)select @r1='',@r2=''select @r1=@r1+yx+',' from ap where id>=3order by 1select @r2=''select @r2=@r2+yx+',' from ap where id>=3order by 1 option(force order)select @r1 r1, @r2 r2
[解决办法]
查资料去,猜测应该和指定的排序有关系,验证中...
[解决办法]
declare @r1 varchar(12) set @r1=''select @r1=@r1+yx+',' from ap where id>=3 order by yxselect @r1/*ccc,ddd,eee,*/declare @r1 varchar(12) set @r1=''select @r1=@r1+yx+',' from ap where id>=3 order by yx option(force order)select @r1/*ccc,ddd,eee,*/declare @r1 varchar(12) set @r1=''select @r1=@r1+yx+',' from ap where id>=3 order by 1select @r1/*eee,*/declare @r1 varchar(12) set @r1=''select @r1=@r1+yx+',' from ap where id>=3 order by 1 option(force order)select @r1/*eee,*/declare @r1 varchar(12) set @r1=''select @r1=@r1+yx+',' from ap where id>=3 order by case when yx='yyy' then '1' else yx endselect @r1/*ccc,ddd,eee,*/declare @r1 varchar(12) set @r1=''select @r1=@r1+yx+',' from ap where id>=3 order by case when yx='yyy' then '1' else yx end option(force order)select @r1/*eee,*/
------解决方案--------------------
呵呵 看不懂
[解决办法]
option(force order)的作用不太清楚,官方说明是质疑使用指定连接方式,但这里明显不会起作用。但加入了这个语句后,优化器把计算字符串的工作放到了第一个标题计算迭代器里,应该是因为有这个语句的存在所以符合了它认为可以直接输出的条件,所以加了以后,实际并没有在计算好的yx+','的结果集里进行累加,而是在开始的计算case when yx='yyy' then '1' else yx end的迭代器里就把字符串计算好了,而且只记录了最后一行而非连接所有。
SELECT @STR=@STR+这种语法应该不是官方支持的字符串累加方式,只是使用者自己找到的方法,所以才会出现不同查询中结果不同。官方推荐的应该还是CLR聚合函数。所以这种问题去官网找答案估计也找不到。
[解决办法]
官方说明是质疑使用指定连接方式,但这里明显不会起作用。但加入了这个语句后,优化器把计算字符串的工作放到了第一个标题计算迭代器里,
[解决办法]
怎么才能增加积分
[解决办法]
不懂,呵呵
[解决办法]
嘿嘿,神奇的东东!
[解决办法]
表示疑惑中,难道和哈希表的生成有关?