简体   繁体   中英

calling a Stored Procedure within a IN clause in SQL Server?

Is it possible to call a stored procedure within a IN clause?

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.

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.

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

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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