在选择查询中使用存储过程

时间:2012-12-15 21:06:05

标签: sql sql-server tsql stored-procedures

我有一个存储过程,我想在SELECT中使用,但是我收到错误。

存储过程的输出是一个包含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

1 个答案:

答案 0 :(得分:2)

不支持从存储过程直接选择。但是,这种类型的操作是table-valued user-defined function的良好候选者,可能类似于:

请注意,您有拼写错误的“转销商”。我已经离开了拼写错误,以便您可以使用现有架构进行测试。

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
)

然后,您可以在查询中包含该功能的联接,或者您可以继续使用IN,这应该类似于:

select * from users where resCode in (SELECT Code FROM getUserResselers(1));