2012-08-29 56 views
0

我在MySQL簡單的SELECT程序

DROP PROCEDURE IF EXISTS `AddNotificationOnPosts`; 

DELIMITER $$ 
CREATE DEFINER=`root`@`localhost` PROCEDURE `AddNotificationOnPosts`(from_user INT(11),on_post_id INT(11),in_group_id INT(11)) 
BEGIN 
    DECLARE num_rows INT DEFAULT 0; 

    SELECT count(notification_id) FROM notifications_posts 
    WHERE from_user = 1; 

END $$ 
DELIMITER ; 

這個過程,這個表

notification_id from_user on_post_id in_group_id date 
2 1 162 3 2012-07-11 12:01:08 
3 19 163 1 2012-07-11 12:03:26 
4 19 164 1 2012-08-10 17:42:36 
5 1 165 3 2012-08-29 12:14:01 
6 1 165 3 2012-08-29 12:14:29 

當我執行:

SET @p0 = '1'; 
SET @p1 = '2'; 
SET @p2 = '3'; 
CALL `AddNotificationOnPosts` (@p0 , @p1 , @p2); 

它給了我:

count(notification_id) 
5 

爲什麼?因爲他們只有3條記錄的user_id 1

,以及如何讓我的這個過程:

  1. 給出錯誤或警告當值不從程序設置

  2. GET變量,像

    SELECT count(notification_id) FROM notifications_posts 
    WHERE from_user = @from_user; 
    
+1

請注意,你硬編碼的過濾器'WHERE FROM_USER = 1' - 你的意思是使用'from_user'參數? – StuartLC

回答

2

您應該使用argume不同的名稱NTS:

CREATE PROCEDURE AddNotificationOnPosts 
(arg_from_user INT(11),arg_on_post_id INT(11),arg_in_group_id INT(11)) 
BEGIN 
    DECLARE num_rows INT DEFAULT 0; 

    IF(arg_from_user IS NULL OR arg_from_user = '') 
    THEN 
     SELECT "Error:Invalid argument for userID" AS error_code; 
    ELSE 
     SELECT count(notification_id) 
     INTO num_rows 
     FROM notifications_posts 
     WHERE from_user = arg_from_user; 
    END IF; 

    SELECT num_rows; 
END $$ 
+0

所以解決方案是重命名變量? – Empeus

+0

是的,錯誤處理的更新代碼。 – Omesh

+0

和「error_code」是保留關鍵字?或者與「SELECT column as cool name」一樣...... ??(ALIAS) – Empeus