简体   繁体   中英

How to select values from a table (SQL Server database) into a parameter (Stored Procedure)?

I am trying to select few values from a table (SQL Server database) into few parameters (Stored Procedure) and here's what I did:

CREATE PROCEDURE [dbo].ValidateStudent
(
    @UserName varchar(50),
    @Password varchar(50),
    @Yes_No int OUTPUT,
    @StudentId int OUTPUT
)
AS
    SET NOCOUNT ON;
SELECT        @Yes_No = COUNT(*)
FROM            Student
WHERE        (UserName = @UserName) AND (Password = @Password)
SELECT        @StudentId = StudentId
FROM            Student
WHERE        (UserName = @UserName) AND (Password = @Password)

Since I am not sure whether it is the right way to achieve what I have mentioned, I need to know few things:

  1. Is it syntactically valid to select 2 values in 2 select statements as in the query above inside 1 stored procedure?
  2. Is the way I have written the query to select values from table into parameter is valid or will work?

Please tell me if the above query is valid and if not then suggest me with the valid query for the same.

Thanks,

You can populate both parameter values with one SELECT

CREATE PROCEDURE [dbo].ValidateStudent
(
    @UserName varchar(50),
    @Password varchar(50),
    @Yes_No int OUTPUT,
    @StudentId int OUTPUT
)
AS
    SET NOCOUNT ON;
SELECT        @StudentId = StudentId, @Yes_No = COUNT(1)
FROM            Student
WHERE        (UserName = @UserName) AND (Password = @Password)
GROUP BY StudentId

That said, wouldn't the value of @Yes_No always be 1, unless you have more than one student with the same UserName and Password ?

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