Reputation:
I have a stored procedure that I want to use in a SELECT
like below but I get an error.
The stored procedure's output is a table with one column of type int
select * from users where resCode in (EXEC getUserResselers 1)
-- stored procedure
create procedure getUserResselers
@userCode int
as
;WITH Directories AS (SELECT code FROM Resseler WHERE code =(select resselerCode from Users where code=@userCode)
UNION ALL SELECT d.code FROM Resseler d INNER JOIN Directories p ON d.parent = p.code)
SELECT * FROM Directories d
Upvotes: 4
Views: 10077
Reputation: 54377
Direct selection from a stored procedure is not supported. However, this type of operation is a good candidate for a table-valued user-defined function, which might look something like:
Note that you have misspelled "resellers". I've left the misspelling so that you could test with your existing schema.
CREATE FUNCTION getUserResselers
(
@UserCode INT
)
RETURNS TABLE AS
RETURN(
WITH Directories AS (
SELECT code FROM Reseller WHERE code = (select resselerCode from Users where code=@userCode)
UNION ALL SELECT d.code FROM Resseler d INNER JOIN Directories p ON d.parent = p.code
)
SELECT * FROM Directories
)
You could then include a join to the function in your query, or you could continue to use IN
, which should be something like:
select * from users where resCode in (SELECT Code FROM getUserResselers(1));
Upvotes: 2