I have a stored procedure that executes a dynamically built string.
It unions several select statements from a constantly changing schema on another server I have no control over (hence the dynamic string). I want to be able to access the results of this procedure from a view, but this is where I get stuck.
I created a stored procedure (code below) which outputs my results to a table, but I want to be able to perform joins, etc. so it would be really convenient if there was some way to wrap this into a view- I'm thinking a table valued function, but I haven't quite figured out how to get the dynamic SQL into a function... any help is appreciated!
CREATE PROCEDURE [dbo].[usp_test]
AS
SET NOCOUNT ON;
DECLARE @sql VARCHAR(MAX)
SELECT @sql = ISNULL(@sql+'
','')+'SELECT TOP (900) *
FROM OPENQUERY(Linked_Server,
'SELECT col1, col2, col3
FROM dbo.'+ tableName+'
+'
UNION' FROM dbo.ls_views
--dbo.ls_views is a view with the pertinent views/table names from the other server.
Set @sql = @sql+ '
Select top (0) ''1'', ''2'',''3'' from sys.tables '
--last select statement is to end multiple unions... not sure if there is a better way, but this works.
--PRINT (@sql);
--EXEC (@sql);
EXECUTE sp_Executesql @sql
GO
Can you have SQL Agent execute this periodically and dump the results into another table/set of tables in your db?
Then you could use it as a straight join in whatever query you want.
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.