2009-11-11 167 views
1

我正在使用Microsoft SQL Server 2005.插入随机选择的记录SQL

我创建了一个随机记录生成器,它将随机插入10个记录到临时表中。临时表中的记录将用于更新内存中表中的记录。

这里是给我一些麻烦的陈述(假设临时表已经创建)。

insert into #tempTable 
    select top (10 - @totalOverShort) 
     d.depositid, d.location, d.amount, d.count, d.user_add, 
     d.date_add, d.status, d.comments, d.subtotal_difference, d.count_difference, d.user_checked, 
     d.date_updated, d.ip_checked, newID() as randomColumn 
    from 
     closing_balance..cb_depositbag as d 
     left join 
     #tempTable as t on d.depositid <> t.depositid and d.location <> t.location 
    where 
     d.date_add between @weekPrior and @weekPriorNight and 
     d.status = 'R' and d.depositID <> t.depositID 
    order by 
     randomColumn 

这条语句给我随机生成的列,但有时(约1/10)我在临时表中得到1个或多个副本。内存中的表格具有2部分密钥,存储ID和位置。我想说,如果没有退出随机选择的(存款ID,位置)对,那么将该记录插入到临时表中。有没有另一种方法来做到这一点?我在想,存在重复的原因是因为它将评估选择语句10次以上,因为它是随机排序的,可能会导致重复。虽然我不确定。

在此先感谢。

回答

4

尝试添加DISTINCT。这应该删除重复的存款ID,位置对。

但是,你想也需要把NEWID()只在ORDER BY并删除 “randomColumn”

编辑:取出1 = 1。没有用。

评论后:但是,这可能不会给你10行,如果内部查询给愚弄......

select DISTINCT * 
FROM 
(
select top (10 - @totalOverShort) 
    d.depositid, d.location, d.amount, d.count, d.user_add, 
    d.date_add, d.status, d.comments, d.subtotal_difference, d.count_difference, d.user_checked, 
    d.date_updated, d.ip_checked 
from 
    closing_balance..cb_depositbag as d 
    left join 
    #tempTable as t on d.depositid <> t.depositid and d.location <> t.location 
where 
    d.date_add between @weekPrior and @weekPriorNight and 
    d.status = 'R' and d.depositID <> t.depositID 
order by 
    newid() 
) foo 
+0

我试过,但得到了下面的错误信息。 如果指定了SELECT DISTINCT,则ORDER BY项目必须出现在选择列表中。 – Aaron 2009-11-11 21:09:41

+0

@Aaron:哈哈!当然! – gbn 2009-11-11 21:12:48

+0

..和更新的答案 – gbn 2009-11-11 21:15:53

0

使用WHERE NOT EXISTS:

insert into #tempTable 
    select top (10 - @totalOverShort) 
     d.depositid, d.location, d.amount, d.count, d.user_add, 
     d.date_add, d.status, d.comments, d.subtotal_difference, 
     d.count_difference, d.user_checked, 
     d.date_updated, d.ip_checked, newID() as randomColumn 
    from 
     closing_balance..cb_depositbag as d 
     left join 
     #tempTable as t on d.depositid <> t.depositid and d.location <> t.location 
    where 
     d.date_add between @weekPrior and @weekPriorNight and 
     d.status = 'R' and d.depositID <> t.depositID order by  randomColumn 

WHERE NOT EXISTS 
(SELECT 1 
FROM #tempTable 
WHERE depositid = d.depositid);