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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With