【问题标题】:SQL Server - Call stored procedure in a IN Statement [duplicate]SQL Server - 在 IN 语句中调用存储过程 [重复]
【发布时间】:2014-03-27 17:22:38
【问题描述】:

首先,有没有可能?

我有一个如下所示的存储过程:

SELECT this FROM table WHERE this IN (SELECT that FROM another_table WHERE that = @Param)

我想用另一个存储过程替换(SELECT that FROM another_table WHERE that = @Param)

我很难找到正确的语法来使它工作。我试过了:

SELECT this FROM table WHERE this IN (EXEC new_stored_procedure @Param)

但这不起作用。有人知道这样做的正确语法吗?

感谢您的帮助

【问题讨论】:

  • 不,这是不可能的。您必须先执行存储过程,并将结果存储到临时表(或表变量)中,然后在 IN 子句中使用 SELECT .. FROM ...
  • 您是否使用 DML 进行 SP?
  • 不幸的是,确实如此。否则,我会使用一个函数。

标签: sql sql-server sql-server-2008 tsql stored-procedures


【解决方案1】:

你可以创建一个临时表

-- match exact columns with datatype returned from the stored procedure
create table #temp(col1 int, col2 .... ) 

insert into #temp(col1,...)
EXEC new_stored_procedure @Param


SELECT this FROM table WHERE this IN (select col from #temp)

【讨论】:

    【解决方案2】:

    您可以使用表值函数

    CREATE FUNCTION [dbo].[Get10Companies]
    (   
     @DepartmentId Int
    )
    RETURNS TABLE 
    AS
    RETURN 
    (
        -- Add the SELECT statement with parameter references here
        SELECT TOP (10) ID from company
                WHERE DepartmentId = @DepartmentId
    )
    
    
     SELECT * from ( Select * from Get10Companies (1104)) t
    

    【讨论】:

    • 我简化了查询,但实际上new_stored_procedure应该做一个插入,这个函数不能做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多