generate id by procedure | mysql

作成時は、delimiter // で ; を変えておく必要があります。

autoincrementのIDを作成して返します。

mysql > delimiter //
 CREATE PROCEDURE check_user (IN s_id VARCHAR(255), OUT r_id INT(11))
 BEGIN
   SELECT id INTO r_id FROM users WHERE authid=s_id;
   IF r_id is NULL THEN
     INSERT INTO users( authid ) values( s_id );
     SELECT id INTO r_id FROM users WHERE authid=s_id; 
   END IF;
END
//
mysql > delimiter ;
mysql> call check_user('test2',@id); select @id; 
Query OK, 1 row affected (0.00 sec)

+------+
| @id  |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

mysql> call check_user('test3',@id); select @id;
    -> //
Query OK, 1 row affected (0.00 sec)

+------+
| @id  |
+------+
|    2 |
+------+
1 row in set (0.00 sec)


mysql> call check_user('test2',@id); select @id;
Query OK, 1 row affected (0.00 sec)

+------+
| @id  |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

test2,test3を追加して、test2を見るとidは1が取得できるという例です。

This entry was posted on 水曜日, 12月 14th, 2011 at 6:47 PM and is filed under mysql. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Unityによるゲームを公開しております iOS/Android
https://itunes.apple.com/jp/app/lost-knight-3d-action/id900917032
https://play.google.com/store/apps/details?id=com.groundroad.runknight

各種開発支援・機能開発等小さいお仕事などもお請けしております。
unity開発支援, PHPシステム開発, javascript/html5 フロント開発, titanium mobileアプリ開発
お気軽にお問い合わせください
大崎・五反田近郊での対面でのお打ち合わせはいつでも可能です。