插入随机选择的记录SQL

时间:2009-11-11 20:57:13

标签: sql sql-server sql-server-2005 tsql

我正在使用Microsoft SQL Server 2005。

我正在创建一个随机记录生成器,它会将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个或多个重复项。内存中的表有一个由两部分组成的键,即DepositID和Location。我想说,如果没有退出随机选择的(depositID,location)对,则将该记录插入临时表。还有另一种方法吗?我认为存在重复的原因是因为它正在评估select语句超过10次,因为它是随机排序的,可能会导致重复。我不确定。

提前致谢。

2 个答案:

答案 0 :(得分:4)

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

但是,您还需要将NEWID()仅添加到ORDER BY并删除“randomColumn”

编辑:删除1 = 1。这毫无意义。

评论之后:但是,如果内部查询给出了dupes,这可能不会给你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

答案 1 :(得分: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);