2016-05-24 29 views
0

中的查詢條件我想寫下面的查詢,但我不是很舒服的SQL。 我孤立插入和更新,它的工作原理,但我不能做條件控制。 我不明白爲什麼它總是失敗,能幫助我嗎?我不明白如何檢查sql

IF (SELECT * FROM Infopoints WHERE name = @name) THEN 
    BEGIN 
     INSERT INTO Infopoints (idInfopoint, createdAt, updatedAt, name) 
     VALUES(@idInfopoint, @createdAt, @updatedAt, @name) 
    END; 
    ELSE 
    BEGIN 
     UPDATE Infopoints SET updatedAt = @updatedAt WHERE name = @name; 
    END; 
ENDIF;"; 

回答

0

你想要on duplicate key update。我認爲邏輯是:

INSERT INTO Infopoints (idInfopoint, createdAt, updatedAt, name) 
     VALUES(@idInfopoint, @createdAt, @updatedAt, @name) 
     ON DUPLICATE KEY UPDATE updatedAt = @updatedAt; 

對於這個工作,你需要name唯一索引:

CREATE UNIQUE INDEX idx_infopoints_name ON infopoints(name); 

要爲IF的邏輯是:

IF NOT EXISTS (SELECT * FROM Infopoints WHERE name = @name) THEN 
. . . 

但是,ON DUPLICATE KEY UPDATE是更好的方法。

0

您的IF條件語法關,試試這個來代替:

If Not Exists (Select * From Infopoints Where Name = @Name) 
Begin 
    Insert Into Infopoints 
       (idInfopoint, createdAt, updatedAt, name) 
    Values  (@idInfopoint, @createdAt, @updatedAt, @name) 
End 
Else 
Begin 
    Update Infopoints 
    Set  UpdatedAt = @UpdatedAt 
    Where Name = @Name 
End