I'm trying to write a procedure which returns values on the basis of a select query result. Like find the ID of a user, use first name and last name to locate a user ID, and return the ID as an OUTPUT parameter. If more than one or no user is found, set a return value of -1, and set the OUTPUT parameter to 0.
I've tried the following code but I'm getting an error:
Must declare the scalar variable "@intValue"
I've search over the internet but none solved my problem.
CREATE PROCEDURE GetIdOfUser
(@f_name VARCHAR(50),
@l_name VARCHAR(50),
@outValue INT OUTPUT)
AS
DECLARE @intValue INT;
SELECT @intValue = userID
FROM users
WHERE firstName = @f_name AND lastName = @l_name
IF @@rowcount > 1 -- more than one user?
BEGIN
SET @outValue = 0
RETURN -1;
END
IF @@rowcount == 1
BEGIN
SET @outValue = @intValue;
END
DECLARE @myretValue INT;
EXEC GetIdOfUser 'raj', 'ahuja', @myretValue;
SELECT @myretValue;
I am using SQLfiddle[sqlfiddle.com] for learning SQL Server concepts. I'm quite new to creating procedures in SQL Server so any help would be appreciated.
EDIT 1: SQL Server Version is 2017
EDIT 2: Schema and sample data that I'm working with.
create table users
(
userID int,
firstName varchar(50),
lastName varchar(50),
title varchar(50)
);
insert into users(userID, firstName, lastName, title)
values(501, 'natasha', 'ghosh', 'title1'),
(502, 'raj', 'ahuja', 'title2'),
(503, 'katy', 'perry', 'title3'),
(504, 'john', 'cyrus', 'title4'),
(505, 'anindita', 'pal', 'title5');