2012-07-26 64 views
1

我對DECLARE,CALL函數和IF settelment有一些麻煩。我至今是:MySQL INSERT WHERE變量不重複

CREATE PROCEDURE number_of_projects(project_name VARCHAR) 
BEGIN 
    DECLARE variable INT; 
    SET variable = 4; 
    SELECT variable; 

    SELECT count(project_id) FROM atm_projects WHERE project_name = variable; 
END 

IF number_of_projects("PROJECT NAME") = 0 
    THEN 
    INSERT INTO atm_projects(project_id,project_name,added_from_mti) 
    VALUES (project_id,'PROJECT NAME',1) 
ENDIF 

的主要目標是將行插入其中project_name不重複的表。

我可以將project_name更改爲UNIQUE密鑰,但請告訴我我的代碼有什麼問題,我該如何解決這個問題?

我需要了解一個PROCEDURE,CALLprocedure,IF是如何工作的。

+0

不能使用'if'聲明函數,觸發器或過程之外。並且你的程序周圍缺少分隔符。 – 2012-07-26 11:05:48

回答

0

您已聲明project_name爲varchar,但未指定長度。將其更改爲VARCHAR(100)

1

嘗試:

CREATE PROCEDURE number_of_projects(project_name VARCHAR(255)) 
BEGIN 
    DECLARE var_project_no INT; 
    SET var_project_no = 0; 
    SELECT var_project_no; 

    SELECT count(project_id) INTO var_project_no FROM atm_projects WHERE var_project_name = 4; 


    IF var_project_no = 0 
    THEN 
     INSERT INTO atm_projects(project_id,project_name,added_from_mti) 
     VALUES (project_id,'PROJECT NAME',1) 
    END IF; 
END; 
+0

我只需要檢查,如果project_name不像「PROJECT1」==「PROJECT1」重複,另一件事,PROCEDURE就像一個函數,在PHP中的方法? – Empeus 2012-07-26 11:27:11

+0

和一件事我怎麼把這個** SELECT計數(project_id)INTO var_project_no從atm_projects WHERE project_name ='PROJECT NAME'; **到一個變量? – Empeus 2012-07-26 11:29:40

+0

使用INTO子句你可以做到這一點。沒有它與PHP函數有所不同,存儲過程(sp)基本上是一組查詢和其他條件。你可以在mysql中創建函數,它可以返回值,但不能。 – Omesh 2012-07-26 11:36:35

0
CREATE PROCEDURE number_of_projects(project_name VARCHAR(255)) 
BEGIN 

if NOT exists(SELECT Top 1 1 FROM atm_projects WHERE var_project_name = 4) 
BEGIN 
    INSERT INTO atm_projects(project_id,project_name,added_from_mti) 
    Select project_id,project_name ,1 
END 
END;