如何在select语句中设置2个计算出的输出参数

时间:2018-09-24 01:49:44

标签: sql-server tsql

我将在SQL Server 2016中创建一个存储过程,基本上,我将验证用户名和密码的组合以了解用户是否有效,如果是的话,我想设置两个OUTPUT参数,其中一个包含一个布尔值,表示该用户有效(因为稍后在我的应用中,我想检查该bool值),而另一个包含该用户的ID。

我的SPROC看起来像这样

ALTER PROCEDURE [dbo].[uspLogin]
(
    @Email AS VARCHAR(200),
    @Password AS VARCHAR(200),
    @IsValid AS BIT OUTPUT,
    @UserId AS INT OUTPUT
)
AS
BEGIN

    SET NOCOUNT ON;

    BEGIN TRY


        BEGIN TRANSACTION;

        SELECT 
        @IsValid = (CASE WHEN COUNT(*) > 0 THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END),
        @UserId = (CASE WHEN COUNT(*) > 0 THEN CAST(U.UserId AS INT) ELSE CAST(-1 AS INT) END)
        FROM [dbo].[User] AS U
        INNER JOIN [dbo].[UserEnabled] AS UE ON U.UserId = UE.UserId
        WHERE U.Email = @Email AND U.Password = @Password

        COMMIT TRANSACTION;

    END TRY
    BEGIN CATCH

        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

        DECLARE @ErrorMessage nvarchar(4000) = 'Error: [' + ERROR_MESSAGE() + '] in line [' + CAST(ERROR_LINE() AS varchar(1000)) + '] of procedure [' + ERROR_PROCEDURE() + ']';

        RAISERROR(@Errormessage, 18, 0);

    END CATCH;

END

执行后,出现此错误:

  

'dbo.User.UserId'列在选择列表中无效,因为它既不包含在聚合函数中也不在GROUP BY子句中。

1 个答案:

答案 0 :(得分:3)

您可以简单地获取@UserId并检查其值。如果为NULL则表示无效

SELECT @UserId  = U.UserId 
FROM   [dbo].[User] AS U
       INNER JOIN [dbo].[UserEnabled] AS UE ON U.UserId = UE.UserId
WHERE  U.Email = @Email AND U.Password = @Password

SELECT @IsValid = CASE WHEN @UserId IS NULL THEN 0 ELSE 1 END

或者,您可以将@IsValid初始化为false并在查询中设置为TRUE

SELECT @IsValid  = 0

SELECT @UserId  = U.UserId,
       @IsValid = 1
FROM   [dbo].[User] AS U
       INNER JOIN [dbo].[UserEnabled] AS UE ON U.UserId = UE.UserId
WHERE  U.Email = @Email AND U.Password = @Password