阻止在SQL Server中显示重复记录

时间:2012-07-14 13:21:12

标签: sql-server stored-procedures

我在SQL服务器中使用存储过程,但它给了我一些重复的记录,当然我的数据库中没有重复的记录,但是我的存储过程给了我两个相同记录的实例,什么可能是错的?如何防止我的查询提供重复记录? 这是我的SP select子句:

select  (ROW_NUMBER() OVER (ORDER BY Review.Point desc) ) as rownumber, 

Business.BusinessId,Business.BName,Business.BAddress1
  ,Business.BAddress2,Business.BCity,Business.BState,Business.BZipCode,Business.countryCode,Business.BPhone1,Business.BPhone2,Business.BEmail,Business.Keyword
  ,Business.BWebAddress,Business.BCatId,Business.BSubCatId,Business.BDetail,Business.bImage,Business.UCId,Business.UCConfirm
  ,Business.UOId,Business.UOConfirm,Business.x,Business.y,Cat.CatName,SubCat1.SubCatName
 from Business left outer join 
        Review on business.BusinessId=Review.BusinessId left outer join
        Cat  on business.BCatid=Cat.CatId  left outer join 
        SubCat1  on business.BSubCatid=SubCat1.SubCatId '+@sql2+' 
) as tbl
where rownumber between  '+CONVERT(varchar, @lbound)+' and '+CONVERT(varchar, @ubound);

3 个答案:

答案 0 :(得分:1)

我不知道您的数据需要深入了解您的连接逻辑,但如果它在BusinessID中重复,您可以为重复项添加另一个ROW_NUMBER()

select  (ROW_NUMBER() OVER (ORDER BY Review.Point desc) ) as rownumber, 
r = ROW_NUMBER()OVER(PARTITION BY Business.BusinessId ORDER BY Business.BusinessId)
Business.BusinessId,Business.BName,Business.BAddress1
  ,Business.BAddress2,Business.BCity,Business.BState,Business.BZipCode,Business.countryCode,Business.BPhone1,Business.BPhone2,Business.BEmail,Business.Keyword
  ,Business.BWebAddress,Business.BCatId,Business.BSubCatId,Business.BDetail,Business.bImage,Business.UCId,Business.UCConfirm
  ,Business.UOId,Business.UOConfirm,Business.x,Business.y,Cat.CatName,SubCat1.SubCatName
 from Business left outer join 
        Review on business.BusinessId=Review.BusinessId left outer join
        Cat  on business.BCatid=Cat.CatId  left outer join 
        SubCat1  on business.BSubCatid=SubCat1.SubCatId '+@sql2+' 
) as tbl
where rownumber between  '+CONVERT(varchar, @lbound)+' and '+CONVERT(varchar, @ubound)
AND r = 1;

答案 1 :(得分:0)

在查询中包含保留字DISTINCT。

例如

select distinct 
    *
from
    students s
    inner join enrollments e on e.StudentId = s.Id
    inner join courses c on c.Id = e.CourseId

但是,结果表中的意外重复通常(但不总是)是一个线索,表明您的查询格式错误或数据库设计糟糕。

答案 2 :(得分:0)

尝试删除此左连接

Review on business.BusinessId=Review.BusinessId left outer join 
您的查询中似乎不需要

,并且对于一项业务有多个评论...