如何将子查询用作存储过程的一部分 MySQL

How to use a sub query as part of a stored procedure MySQL

我正在尝试创建一个过程(在 phpMyAdmin 中称为例程)并且当前有以下查询:

BEGIN

INSERT INTO `users` (`username`, `password`, `email`, `user_role_id`,` date_registered`)
    VALUES (_username, _password, _email, (SELECT `ID` FROM `roles` WHERE `role_name` = _role) , _date);

END;

但这行不通,我已经尝试向 role_ID 声明一个变量,但这也行不通,有人可以帮我解决这个问题吗?

注意

您看到的参数(以下划线开头(_))都是IN phpMyAdmin routine creator

中使用的参数

编辑

我试过的其他代码是这样的:

BEGIN

DECLARE role_id AS/*=*/ (SELECT `ID` FROM `roles` WHERE `role_name` = _role); /* tried both AS and = */

INSERT INTO `users` (`username`, `password`, `email`, `user_role_id`, `date_registered`)
    VALUES (_username, _password, _email, role_id, _date);

END;

还注意到 DECLARE 的一个小错误,将上面的代码更改为:

BEGIN

DECLARE @role_id ;
SET @role_id = (SELECT `ID` FROM `roles` WHERE `role_name` = _role);

INSERT INTO `users` (`username`, `password`, `email`, `user_role_id`, `date_registered`)
    VALUES (_username, _password, _email, @role_id, _date);

END;

但还是没有运气

我已经弄清楚如何做到这一点 - 虽然没有使用子查询,但我有这个存储过程:

BEGIN

INSERT INTO `users` (`username`, `password`, `email`, `user_role_ID`, `date_registered`)
    VALUES (username, pwd, email, role, datenow);

END

和这个 PHP 函数和 class 来运行它:

class create_user
{
    public static function CreateUser($username, $password, $email, $role)
    {
        global $link;
        #region Get role id
        $role_q = "SELECT `ID` FROM `roles` WHERE `role_name` = '{$role}';";
        $role_rs = mysqli_fetch_row($link->query($role_q));
        $role = $role_rs[0];
        #endregion

        #region Create user
        $link->query("CALL sp_create_user('{$username}', '" . hash("sha256", $password) . "', '{$email}', '{$role}', '" . date("y-m-d H:i:s") . "')") ? $inserted = true : $inserted = false;
        #endregion

        #region check if user created
        if ($inserted)
        {
            return true;
        }
        else
        {
            return "User was not created. Either the username or email is already in use.";
        }
        #endregion
    }
}

如果有人可以用子查询做到这一点,那将是正确的答案,但不是我问题的完整答案。

SQL 快乐!

USE [FydaDB]
GO
/****** Object:  StoredProcedure [dbo].[CountryManagerReport]    Script Date: 5/25/2018 2:12:42 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[CountryManagerReport] 
    @FromDate datetime,
    @Todate datetime,
    @countryId int
AS
BEGIN
Select FirstName+ ' ' + MiddleName+ '' +  LastName as FullName ,Email,CNIC,((select CountryCode from Country where ID=FydaAdmin.CountryId)+ '-' +(select PhoneNo from Contacts where FydaAdminId=FydaAdmin.ID)) as Mobile,
(ZipCode+ ' ,' +[Address]+ ' ,' + (select Name from City where ID=FydaAdmin.CityId )+ ', ' +(select Name from States where ID=FydaAdmin.StateId )+ ', ' +(select Name from Country where ID=FydaAdmin.CountryId)
 ) as [Address]
 from FydaAdmin where CreatedDateTime  BETWEEN  @FromDate  and @Todate or CountryId=@countryId 
END