2012-03-02 43 views
1

表-A:SQL插入新行只有在對不存在兩列(IDS)以前

id | user_id | stage_id | create_date 

表-B:

id | stage_id | template_id | name | description | create_date 

我通過一個表格數據保存到這些帶有ajax調用的頁面。我的問題是我只想在Table_A中插入一個新行,如果stage_id user_id配對是唯一的。

例子我不想,表-A的:

id user_id stage_id create_date 
0129 | 24321 | 3202393 | 01/12/12 
0129 | 39234 | 3202393 | 01/12/12 
2329 | 39234 | 3202393 | 01/14/12 
3459 | 39234 | 3202393 | 01/15/12 

^這是我不希望發生的事情,來處理這個沒有什麼好的辦法?

它應該是:

id user_id stage_id create_date 
0129 | 24321 | 3202393 | 01/12/12 
0129 | 39234 | 3202393 | 01/12/12 

執行通過PHP類查詢,在這個過於簡單的例子:

$query = 'INSERT INTO Table_A ('. 
      'id, '. 
      'user_id, '. 
      'stage_id, '. 
      'create_date '. 
      ') OUTPUT inserted.id '. 
      'VALUES ('. 
       'newid(), '. 
       '%s, '. 
       '%s, '. 
       'getdate()'. 
     ')'; 

$this->db->Execute($query); 

可能失去了一些東西愚蠢的,但我以爲有人也許能夠把我在正確的方向,謝謝!

+0

不表-B在你的問題中發揮作用? – Colin 2012-03-02 01:41:54

回答

3

我只想查詢表中,以查看是否值已經存在於你的stage_id,USER_ID對。

所以像:

if not exists (select * from table_A where user_id = @myUserID and stage_id = @myStageID) 
begin 
insert into ... 
end 
相關問題