سؤال

I am trying to make a stored procedure call AddCluster witch is taking to parameter 'title' and 'alt'

Case 1:

If 'title' is in the db then just return the "old" row!

Case 2:

If the 'title' is NOT in the db then,

insert a row base on parmerer 'title' and 'alt'

and then select the newly added row via LAST_INSERT_ID()

The problem is on case 2 it only returns empty!!

-- --------------------------------------------------------------------------------
-- AddCluster Group Routines
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`linkbay_dk`@`%` PROCEDURE `AddCluster`(in in_title varchar(45), in in_alt text)
BEGIN
    /* check if 'in_title' is in db */
    IF EXISTS
    (
        SELECT count(*) FROM Cluster 
        WHERE title=in_title 
    )
    THEN
        /* returns old Cluster there is in db */
        SELECT * FROM Cluster WHERE title=in_title; 
    ELSE
        INSERT INTO Cluster
        (
            `id`,
            `create_at`,
            `title`,
            `alt`
        )
        VALUES
        (
            null,
            NOW(),
            in_title,
            in_alt
        );
        /* returns the newly added Cluster */
        SELECT * FROM Cluster WHERE id=LAST_INSERT_ID();
    END IF;
END$$
هل كانت مفيدة؟

المحلول 2

Just a little update. I find the error.. Which is count(*)

SELECT count(*) FROM Cluster WHERE title=in_title 

It should be like this:

SELECT * FROM Cluster WHERE title=in_title

See the hole update stored procedure here!

نصائح أخرى

Try to INSERT without specifying an id :

...
ELSE
    INSERT INTO Cluster
    (
        `create_at`,
        `title`,
        `alt`
    )
    VALUES
    (
        NOW(),
        in_title,
        in_alt
    );
    /* returns the newly added Cluster */
    ...

Make sure Cluster.id is an AUTO_INCREMENT column, only that way you can obtain the value with LAST_INSERT_ID().

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top