Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IF EXISTS with a stored procedure as argument

I have a stored procedure called 'authenticate' that returns me the user profile record if provided correct username and password. Now I am trying to get all users in system if 'authenticate' stored procedure returned me a record otherwise return nothing. I am trying something like this:

IF EXISTS EXECUTE authenticate @UserName, @Password
BEGIN    
    SELECT * from Users;
END

I am getting error: Incorrect syntax near the keyword 'EXECUTE'. Any ideas what am I doing wrong?

like image 803
shaffooo Avatar asked Oct 16 '25 16:10

shaffooo


2 Answers

You can transform your procedure into function:

create function dbo.authenticate(@UserName varchar(50), @Password varchar(50))
returns @found table(userName varchar(50), userPass varchar(50)) as
begin
  -- some of your internal table
  declare @user table (userName varchar(50), userPass varchar(50));
  insert into @user values ('John', '123'), ('Jack', '345');

  insert into @found (userName, userPass)
    select
      u.userName, u.userPass
    from
      @user u
    where
      u.userName = @UserName and u.userPass = @Password
  ;

  return;

end;

go

if exists(select * from dbo.authenticate('John', '123')) begin
  print 'exists';
end;
like image 102
Slava N. Avatar answered Oct 18 '25 09:10

Slava N.


EXISTS takes a SELECT subquery not the results of a stored procedure. See MSDN. You will need to either replicate your SELECT from authenticate in your EXISTS statement or populate a table with the results prior to the EXISTS. e.g.

INSERT INTO #authenticate (col1, col2, col3)
EXEC authenticate @UserName, @Password

IF EXISTS (SELECT 1 FROM #authenticate)
BEGIN    
    SELECT * from Users;
END
like image 23
strickt01 Avatar answered Oct 18 '25 09:10

strickt01



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!