2011-01-24 69 views
1

我期待每天只向數據庫插入一次數據。問題是我想用sql查詢來檢查它(因爲代碼是不可觸及的)每天調用一次插入

當前任何時候任何人訪問某個網頁時,都會調用spInsertRate過程。

INSERT INTO dbo.LU_ExchangeRates 
(exch_Date,exch_Currency,exch_Rate) 
VALUES(@exchDATE,@exchCurrency,@exchRate) 

我猜我必須首先做一個SELECT語句,如果select語句不返回行,這意味着運行插入語句。我只是無法弄清楚如何爲此編寫代碼。

+0

如果發生這種情況,您可能會遇到一些設計問題當前任何時候任何人訪問某個網頁時都會調用spInsertRate過程。什麼速率正在插入,或者每個貨幣有一次? – RichardTheKiwi

回答

4

,如果你一定要做到爲單一SQL這將工作

INSERT INTO dbo.LU_ExchangeRates 
(exch_Date,exch_Currency,exch_Rate) 
SELECT 
    @exchDATE,@exchCurrency,@exchRate 
WHERE 
    NOT EXISTS ( 
     SELECT * from dbo.LU_ExchangeRates 
     WHERE 
      exch_Date = @exchDATE and exch_Currency = @exchCurrency) 

但其更經常可以看到

IF NOT EXISTS ( 
      SELECT * from dbo.LU_ExchangeRates 
      WHERE 
       exch_Date = @exchDATE and exch_Currency = @exchCurrency) 

    INSERT INTO dbo.LU_ExchangeRates 
    (exch_Date,exch_Currency,exch_Rate) 
    VALUES 
     @exchDATE,@exchCurrency,@exchRate 
+0

+1爲前者不需要IF – RichardTheKiwi

4

我將一個唯一的約束放在exch_Date列上,然後讓spInsertRate運行插入並捕獲異常(如果失敗)。

+0

具體說明前端代碼是不能改變的。 – RichardTheKiwi

+2

這與前端代碼無關。當違反約束時會引發T-SQL異常。這些可以被抓到SP內部,並酌情吞服。 –

1
IF NOT EXISTS (SELECT * FROM dbo.LU_ExchangeRates WHERE exch_Date = @exchDATE) 
BEGIN 
INSERT INTO dbo.LU_ExchangeRates (exch_Date,exch_Currency,exch_Rate) VALUES(@exchDATE,@exchCurrency,@exchRate) 
END 
0

我會做,做它的插入,如果一個查詢在表中找不到今天的日期。這樣你就不會在選擇插入物之間進行競爭。也許

INSERT INTO dbo.LU_ExchangeRates (...) 
SELECT @exchDate, ... 
WHERE NOT EXISTS (SELECT * 
        FROM dbo.LU_ExchangeRates 
        WHERE exch_date >= @exchDate 
        AND exch_Currency != @exchCurrency) 
+0

[這仍然有競爭條件。](http://stackoverflow.com/questions/3407857/only-inserting-a-row-if-its-not-already -那裏) –

1

您可以定義與IGNORE_DUP_ROWS選項的複合唯一索引(或什麼是它的名字),然後任何失敗的插入都將被丟棄。

這可以在Sybase ASE上完成,也許不在MS SQL服務器上完成。