简体   繁体   中英

How to get a single column's value from a stored procedure call within a stored procedure?

I have the following procedure:

SP_Validate_User_Main
(
  @UserName VARCHAR(20),
  @Password VARCHAR(20),
  @From VARCHAR(10),
  @IP VARCHAR(15)
)

-- does a bunch of stuff, then the following line is the last to execute

EXECUTE SP_Validate_User @aUserName = @UserName, @aPassword = @Password

Depending on the validity of the data passed to SP_Validate_User , 1 of 2 statements will then get executed:

SELECT 
    someNumber AS ErrorCode, 
    otherNumber AS AttemptsRemaining, 
    thirdNumber AS LockoutTimeRemaining
RETURN

or

SELECT * 
FROM Users 
WHERE ...

RETURN

I'm trying to expand my first procedure, SP_Validate_User_Main , to insert a record into a new audit table every time a user attempts to login, regardless of whether or not it was successful. So I've added these 2 lines to SP_Validate_User_Main :

INSERT INTO LoginAudit (IP, Username, Password, AttemptDate, Result)
VALUES (@IP, @UserName, @Password, GETDATE(), @Result)

How can I assign a value to @Result such that it would contain either ErrorCode or 0 ? If ErrorCode exists in the data set returned by SP_Validate_User , I want that value. If it does not, I want it to contain the value 0 .

I found this SO question:

Select columns from result set of stored procedure

Which seems to be asking what I want, but has no accepted solution and the top-voted answer is inapplicable as SP_Validate_User will return 1 of 2 schemas.

All of the other questions I've found while searching around were in regards to handling the data code-side rather than DB.

Basically, I'm looking for the SQL equivalent of this psuedo-code:

if (resultSet.Columns.Count > 3)
    @Result = 0;
else
    @Result = resultSet["ErrorCode"];

The SP_Validate_User stored proc is the one that is in two parts, one statement that returns an error code, and one that pulls back users, correct?

If this is what's happening, why don't you add the IP parameter to the SP_Validate_User proc, then have two insert statements in that proc, one that inserts if the error condition is met, and one that inserts if the error condition is not met.

INSERT INTO LoginAudit (IP, Username, Password, AttemptDate, Result)
VALUES (@IP, @UserName, @Password, GETDATE(), someNumber)

SELECT 
someNumber AS ErrorCode, 
otherNumber AS AttemptsRemaining, 
thirdNumber AS LockoutTimeRemaining

RETURN

or

INSERT INTO LoginAudit (IP, Username, Password, AttemptDate, Result)
VALUES (@IP, @UserName, @Password, GETDATE(), 0)

SELECT * 
FROM Users 
WHERE ...

RETURN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM