2013-10-25 68 views
0

我使用MS的Visual Studio 2012和MS SQL 2012插入如果不存在SQL

在我的asp.net VB的網頁我有一個4個文本框,用戶可以輸入值,然後單擊插入。然後將這些值與日期,用戶名和一個整數一起傳遞給sql,通過執行第一個文本框值然後第二個等等的子例程。

我的問題是存儲過程。我用一個IF NOT存在來查看錶中的當前數據,如果沒有數據匹配日期和整數,那麼它將插入記錄。然後VB子將傳入第二組數據,它將再次查看日期是否與整數一起出現,等等。該存儲的過程如下:

@price money, 
@datesubmitted datetime, 
@commodityID int, 
@submitted_By nvarchar(10) 

As 
    begin 
    if not exists ((select * from dailyPricing where (convert(date, datesubmitted, 103) = convert(date, @datesubmitted, 103) and commodityID = 1) 
    or 
    (convert(date, datesubmitted, 103) = convert(date, @datesubmitted, 103) and commodityID = 2) 
    or 
    (convert(date, datesubmitted, 103) = convert(date, @datesubmitted, 103) and commodityID = 3) 
    or 
    (convert(date, datesubmitted, 103) = convert(date, @datesubmitted, 103) and commodityID = 4))) 
    Begin 
    INSERT INTO dailyPricing (price, datesubmitted, commodityID, submitted_By) 
    values(@price, @datesubmitted, @commodityID, @submitted_By) 

end 
end 

的上述結果是,它只進入值的第一組,而不是第二,第三或第四。我調試了我的VB代碼,它工作正常,我只是覺得我沒有正確地形成SQL。

+1

你需要用MERGE語句,就像這樣:http://stackoverflow.com/a/10219581/1734130 – mvp

+0

在你的存在,你總是比較@commodityID。你打算比較你的數據庫字段的商品ID嗎? – fan711

+0

它應該查看數據庫中的日期是否匹配@datesubmitted,並且是否有一個與1,2,3或4匹配的商品ID。如果沒有任何操作,如果沒有,則插入該行。我還修改了上面的代碼,刪除了@前面的商品ID。 – Silentbob

回答

1

我認爲你需要重寫「不存在」的每一個檢查嘗試這樣的事情,我認爲你需要更新他們可能是錯誤的括號:

if not exists ((select * from dailyPricing where 
    (convert(date, datesubmitted, 103) 
    = convert(date, @datesubmitted, 103) and commodityID = 1) 

if not exists ((select * from dailyPricing where 
    (convert(date, datesubmitted, 103) 
    = convert(date, @datesubmitted, 103) and commodityID = 2) 

或 ....

+0

謝謝謝克爾我用你的例子,但我刪除了if'或最後3條語句,所以它剛剛開始不存在 – Silentbob