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

MS_SQL是我的错还是你的错?
SQL code

--上下的查询语句是一样的只是将AwardsID判断的值一个是用自定义的变量一个是写死的数值
--为什么查出来的数据就不样
--查询环境一样,同时执行,查询时候未对数据进行任何更改,也没有使用过什么触发器之内的约束
declare @awards_Id int
set @awards_Id=1
select top(1) ContestantID,ContestantName,AwardsID,VotesNumber,3 from XYYSJBS_ContestantBYAwardsID_VML 
where AwardsID=@awards_Id and ContestantID not in(select top(2) ContestantID from XYYSJBS_ContestantBYAwardsID_VML 
                                                  where AwardsID=@awards_Id order by VotesNumber desc) 
order by VotesNumber desc
print '@awards_Id:'+convert(varchar(2),@awards_Id)
--result-------------
1    张三    1    3    3
-------------------------------------------------------------------
select top(1) ContestantID,ContestantName,AwardsID,VotesNumber,3 from XYYSJBS_ContestantBYAwardsID_VML 
where AwardsID=1 and ContestantID not in(select top(2) ContestantID from XYYSJBS_ContestantBYAwardsID_VML 
                                                  where AwardsID=1 order by VotesNumber desc) 
order by VotesNumber desc
--result-------------
5    钱七    1    3    3


结果集信息

输出消息


------解决方案--------------------
我怀疑VotesNumber 列出现大量重复数据。
SQL code

select top(1) ContestantID,ContestantName,AwardsID,VotesNumber,3 from XYYSJBS_ContestantBYAwardsID_VML 
where AwardsID=1 and ContestantID not in(select top(2) ContestantID from XYYSJBS_ContestantBYAwardsID_VML 
where AwardsID=1 order by VotesNumber desc) 
order by VotesNumber desc

go 10

------解决方案--------------------
楼主把 2段top(1) 去掉,看结果集是不是一样,我估计是排序造成的
------解决方案--------------------
很明显,你的外部查询的top语句没有指定排序字段,所以,每次查询结果就不一样了!
------解决方案--------------------
下面是我猜测的可能会影响的原因:
如果在 where 子句中使用参数,也会导致全表扫描。因为SQL只有在运行时才会解析局部变量,但优化程序不能将访问计划的选择推迟到运行时;它必须在编译时进行选择。然而,如果在编译时建立访问计划,变量的值还是未知的,因而无法作为索引选择的输入项。
因为执行计划会保存以备下次使用,所以写死的查询语句会执行这个执行计划。而用参数的却不会。因为执行计划的不同,所以order by 条件的在都是3的情况下会有不同的结果。

如果是上面的原因,解决这个问题只需要在order by语句的VotesNumber 字段后面再加上一个条件比如ContestantID就可以了
------解决方案--------------------
问题出在VotesNumber列,肯定有大量重复值,当然以它排序,结果是随机的!