2013-07-21 87 views
0

我想寫一個MySQL查詢來更新記錄,如果它存在,否則創建一個新的記錄到2個不同的表。我在網上發現了一些信息,但我似乎無法得到它。如何更新記錄,如果它存在,否則在MySQL中插入新記錄

這是我當前的查詢

Set @time_now := NOW(); 

    if exists(SELECT 1 FROM phone_calls WHERE account_id = 8 AND call_code_id = 5 AND status = 1) 
     BEGIN 
     UPDATE phone_calls 
     SET [email protected]_now, 
     isAppointment=1, 
     modified_by = 2, 
     modified_on = @time_now 
     WHERE account_id =8 AND call_code_id = 5 AND status = 1; 
     END 
    ELSE 
     BEGIN 
     INSERT INTO phone_calls (mid_id, account_id, call_code_id, trigger_on, created_on, call_subject, status, next_call_id 
           , call_direction, owner_id, workflow_generated, call_notes, total_attempts, isAppointment) 
           VALUES (1, 8, 5, @time_now, @time_now, 'This is a test', 1, 0 , "OUTBOUND", 2, 1, "", 0, 0); 
     INSERT INTO inventory_engine_history(phone_call_id, new_phone_call_id, created_by, new_call_owner, action, trigger_on) 
               VALUES(1000, LAST_INSERT_ID(), 2, 2, '', @time_now)'; 
     END 

我遇到了一個語法錯誤

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if exists(SELECT 1 FROM phone_calls WHERE account_id = 8 AND call_code_id = 5 AN' at line 1 

能有人幫我這個錯誤?

注意:如果存在多個記錄,我應該更新所有這些記錄,但如果沒有記錄存在,它們將在每個表中只插入一條記錄。

感謝

回答

0
DECLARE theCount INT; 
SELECT COUNT(*) INTO theCount FROM phone_calls WHERE account_id = 8 AND call_code_id = 5 AND status = 1 
IF(theCount=0) THEN -- DoLogic; 
ELSE -- DoSomeOtherLogic; 
END IF 
+0

感謝您的答案,但我收到一個語法錯誤。 「#1064 - 你的SQL語法錯誤;檢查對應於你的MySQL服務器版本的手冊,在第1行'DECLARE theCount INT'附近使用正確的語法。」同樣在THEN和ELSE之間的部分,我寫我的代碼在BEGIN ... END語句中? – Jaylen

+0

好吧,也許刪除DECLARE並使用SELECT COUNT(*)INTO @theCount ... 我主要是一個T-SQL程序員,所以它有點不同。 –

+0

我明白了,如果我改變你的代碼,我會在行IF(@count> 0)THEN中得到不同的語法錯誤。 – Jaylen

相關問題