I have a stored procedure that is supposed to work as follows:
DECLARE @TagNames AS TABLE
(
tag NVARCHAR(50) NOT NULL
)
-- Get list of tags
INSERT INTO @TagNames
SELECT tag
FROM tagTable
WHERE tag LIKE @tagPattern
-- Create unified result set, combining results from stored proc for each tag
SELECT n.tag, r.time, r.value FROM @TagNames AS n
CROSS APPLY
dbo.GetResultsForTag(n.tag) AS r -- Not valid
However, I can't use CROSS APPLY because dbo.GetResultsForTag()
is a stored procedure.
The implementation of dbo.GetResultsForTag()
relies on calling EXEC
on dynamic SQL passed to a linked server, so I believe it can't be converted into a table-valued function. Dynamic SQL isn't permitted in table-valued functions.
The linked server communicates via an OLE-DB provider, but it's not an SQL Server instance. It's an OSISoft PI process historian database. Normally it's quite easy to query for multiple tags of data in a single query, but in this case I'm doing some calculations which require me to supply a filter expression which specifies a single tag name. So each tag needs a separate query to the data source.
As far as I know, stored procedures can't be used as the right-hand side of a JOIN?
What other options are open to me for consolidating these results together? Just a cursor?
Edit: I've figured out how to fix the underlying obstacles which were forcing me to use dynamic SQL and a stored procedure. Now I can use regular SQL, which allows me to use a Table Valued Function instead of a stored proc, which allows me to use JOIN and CROSS APPLY instead of ugly cursor hacks.