簡體   English   中英

使用在MySQL存儲過程的其他語句中的一個選擇查詢中獲得的結果

[英]Use result obtained in one select query in other statement in MySQL Stored Procedure

我正在編寫一個存儲過程,在該過程中,我將從一個表中獲取數據,並基於該數據,希望在其他操作中使用該數據。 例如

select id,name,email,mobile,user_type from users

並且基於user_type我想使用id字段做進一步的處理。 例如

if(user_type=1) 
   begin
        select * from some_table where Userid = id
   End
Else if (user_type=2)
  begin
      select * from some_other_table where Userid = id
  End

誰能提供基本語法給我

您可以在過程中declare變量,然后使用SELECT ... INTO ... FROM語句填充它們。 然后可以在IF THEN ELSE表達式中使用這些變量。

DELIMITER $$
CREATE PROCEDURE test()
BEGIN
   DECLARE temp_id, temp_user_type INT;
   DECLARE temp_name, temp_email, temp_mobile VARCHAR(100);

   SELECT id,name,email,mobile,user_type 
   INTO temp_id, temp_name, temp_email, temp_mobile, temp_user_type FROM users WHERE id = 1;

   IF temp_user_type = 1 THEN 
        SELECT * FROM some_table WHERE Userid = temp_id     
   ELSEIF temp_user_type = 2 THEN
        SELECT * FROM some_other_table WHERE Userid = temp_id
   ELSE 
        --
   END IF;
END$$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM