2009-11-11 213 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);