Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Results of Stored Procedure in Where clause

I have a Stored Procedure(SP) in MS SQL 2008 R2 I'm building that requires a list of users to narrow down the data returned.

The system I'm working on has a GetUsers SP which returns a list of users, and I need to then use this to limit the results returned from the SP I am working on myself.

I've had a look at TABLE variables, but not sure if this is quite what I need.

How would I go about integrating the results of one SP into the where clause of another SP?

like image 907
Tom Avatar asked Sep 06 '12 09:09

Tom


People also ask

Can I use Stored Procedure in where clause?

It would be better to convert your Stored Procedure into a Function, if possible. Then you can use function in WHERE clause. If you can't convert it into the function then better to execute the SP and stored the full result in Temp Table or Table Variable. Now you can use This table in WHERE clause SUB QUERY.

Can a Stored Procedure return an output value to its caller?

If you specify the output keyword for a parameter in the procedure definition, the procedure can return the current value of the parameter to the calling program when the procedure exits.

How do you find where a Stored Procedure is used?

Using SQL Server Management Studio Expand Databases, expand the database in which the procedure belongs, and then expand Programmability. Expand Stored Procedures, right-click the procedure and then click View Dependencies. View the list of objects that depend on the procedure.

How can we return a value in Stored Procedure?

The RETURN statement is used to unconditionally and immediately terminate an SQL procedure by returning the flow of control to the caller of the stored procedure. It is mandatory that when the RETURN statement is executed that it return an integer value. If the return value is not provided, the default is 0.


2 Answers

You can take the results of your SP by

DECLARE @yourtablevariable TABLE (fields....)    

INSERT INTO @yourtablevariable
EXEC GetUsers

Then

SELECT *
FROM othertable
    INNER JOIN @yourtablevariable users on othertable.userid=users.userid

Or

SELECT *
FROM othertable
WHERE userid in (SELECT UserID FROM @yourtablevariable)

Alternatively, if possible, you could convert GetUsers to a table valued function.

like image 129
podiluska Avatar answered Nov 15 '22 09:11

podiluska


In SQL Server if the SP returns a TABLE, than the best way to use a table variable (@Table) or memory table (#Table) if the returned amount of data is bigger.

like image 37
András Ottó Avatar answered Nov 15 '22 08:11

András Ottó