简体   繁体   English

在SQL Server的IN子句中调用存储过程?

[英]calling a Stored Procedure within a IN clause in SQL Server?

Is it possible to call a stored procedure within a IN clause? 是否可以在IN子句中调用存储过程?

Select field0, field2 FROM Table
WHERE field0 in (exec storedproc)

The reason for stored procedure is because of the complexity of it 存储过程的原因是因为它的复杂性

You could have to use OpenRowset to achieve this. 您可能必须使用OpenRowset来实现此目的。

Select Field0, Field2 From Table
Where Field0 in (
                SELECT Field0 FROM OPENROWSET('SQLNCLI', 
                             'Server=SERVERNAME;Trusted_Connection=yes;',
                            'EXEC StoredProc')
                )

In order to do this the following options must be enabled on the server: 为此,必须在服务器上启用以下选项:

sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO

If it isn't possible to change these settings then another option, as discussed with Martin in the comments, is to populate a temporary table. 如果无法更改这些设置,则在评论中与Martin讨论的另一个选项是填充临时表。

eg 例如

declare @t table
(
Field0 int,
Field1 varchar(100)
...
)

Insert Into @t
Exec storedProcedure

Select Field0, Field2 From Table
Where Field0 in (
                SELECT Field0 FROM @t
                )

To insert the results of the stored procedure to a temporary table the definition of the temporary table must match the results of the stored procedure exactly. 要将存储过程的结果插入临时表,临时表的定义必须与存储过程的结果完全匹配。

Stored procedure cannot be used for such case. 存储过程不能用于此类情况。 But, review possibility to use table-value function that are correct as argument of IN statment 但是,检查使用正确的表值函数作为IN语句的参数的可能性

You can't use a stored proc. 您不能使用存储过程。 You need to use a function that returns a table. 您需要使用返回表的函数。 For example: 例如:

CREATE FUNCTION myFunction(@arg varchar(30))
RETURNS @myTable table(Value INT)
AS
BEGIN
    insert into @myTable(Value) values (1)       
    RETURN
END

Now you can run the function as part of your query: 现在,您可以将该函数作为查询的一部分运行:

Select field0, field2 FROM Table
WHERE field0 in (select Value from myFunction('arg'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM