存储过程通过比较2个字段返回值

时间:2015-07-10 06:16:33

标签: c# sql database stored-procedures

我的表格包含3列USERIDOLDPASSWORDNEWPASSWORD

如果OLDPASSWORD之间存在相等,我想按NEWPASSWORD选择USERIDOLDPASSWORD列并与NEWPASSWORDNEWPASSWORD进行比较和OLDPASSWORD,它应返回NEWPASSWORD,否则返回0(字符串);

像这样:

ALTER PROCEDURE [dbo].[GET_PASSWORD]
(
    @USERID NVARCHAR(50)
)
AS
     SELECT OLDPASSWORD, NEWPASSWORD 
     FROM PASSWORDINFO 
     WHERE USERID = @USERID

     IF OLDPASSWORD == NEWPASSWORD 
        RETURN "0" 
     ELSE 
        RETURN NEWPASSWORD

感谢您的帮助。

6 个答案:

答案 0 :(得分:1)

Return关键字不适用于从表中返回值。 Return关键字用于从存储过程返回,它只能返回整数值。在这里,您可以返回执行proc的代码结果。您应该使用select语句或使用output parameter

直接执行此操作
ALTER PROCEDURE [dbo].[GET_PASSWORD] @USERID NVARCHAR(50)
AS
    BEGIN
        SELECT  CASE WHEN OLDPASSWORD = NEWPASSWORD THEN '0'
                     ELSE NEWPASSWORD
                END AS CurrentPassword
        FROM    PASSWORDINFO
        WHERE   USERID = @USERID
    END

或者:

ALTER PROCEDURE [dbo].[GET_PASSWORD]
    @USERID NVARCHAR(50) ,
    @CurrentPassword NVARCHAR(50) OUTPUT
AS
    BEGIN
        SELECT  @CurrentPassword = CASE WHEN OLDPASSWORD = NEWPASSWORD
                                        THEN '0'
                                        ELSE NEWPASSWORD
                                   END
        FROM    PASSWORDINFO
        WHERE   USERID = @USERID
    END

答案 1 :(得分:0)

你试过这个:

ALTER PROCEDURE [dbo].[GET_PASSWORD]
(
    @USERID NVARCHAR(50)
)
AS
BEGIN

    SELECT
        CASE
            WHEN OLDPASSWORD = NEWPASSWORD THEN '0'
            ELSE NEWPASSWORD
         END
    FROM PASSWORDINFO
    WHERE USERID = @USERID

END

答案 2 :(得分:0)

你需要这样的东西:

   SELECT CASE WHEN OLDPASSWORD = NEWPASSWORD THEN '0' 
   ELSE NEWPASSWORD END AS Result 
   FROM PASSWORDINFO WHERE USERID = @USERID

答案 3 :(得分:0)

ALTER PROCEDURE [dbo].[GET_PASSWORD] (@USERID NVARCHAR(50), @result VARCHAR(10) OUTPUT)
AS
BEGIN
    SELECT @result = CASE 
            WHEN OLDPASSWORD = NEWPASSWORD
                THEN '1'
            ELSE '0'
            END
    FROM PASSWORDINFO
    WHERE UserId = @USERID
END

答案 4 :(得分:0)

使用返回值返回多个值是不可能的,其中作为输出参数,可以返回任何数据类型,并且sp可以具有多个输出参数。我总是喜欢使用输出参数而不是RETURN值。

通常,RETURN值用于指示存储过程的成功或失败,尤其是在我们处理嵌套存储过程时。返回值0,表示成功,任何非零值表示失败。

ALTER PROCEDURE [dbo].[GET_PASSWORD]
    @USERID NVARCHAR(50) ,
    @Password NVARCHAR(50) OUTPUT
AS
    BEGIN
        SELECT  @Password  = CASE WHEN OLDPASSWORD = NEWPASSWORD
                                THEN '0'
                                  ELSE NEWPASSWORD
                                END
        FROM    PASSWORDINFO
        WHERE   USERID = @USERID
    END

答案 5 :(得分:0)

// try this
ALTER PROCEDURE [dbo].[GET_PASSWORD]
(
    @USERID NVARCHAR(50)
)
AS
    declare   @NewPassword NVARCHAR(50)
     declare   @OldPassword NVARCHAR(50)

     SELECT  @OldPassword =OLDPASSWORD, @NewPassword = NEWPASSWORD 
     FROM PASSWORDINFO 
     WHERE USERID = @USERID    

     IF @OldPassword = @NewPassword 
        RETURN "0" 
     ELSE 
        RETURN @NewPassword