Click here to Skip to main content
15,885,954 members
Articles / Database Development / SQL Server / SQL Server 2008

Exporting Stored Procedure Results into Tables Dynamically with T-SQL

Rate me:
Please Sign up or sign in to vote.
4.85/5 (5 votes)
11 Jan 2012CPOL4 min read 41.7K   553   14  
T-SQL Code for Converting Stored Procedure results to Tables Dynamically
/****** Object:  StoredProcedure [dbo].[XportStoredProc]    ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[XportStoredProc]
@SRCOBJECT varchar(500) ,
@SCHEMA varchar(100)= N'dbo'
AS 

/********************************************************************** 
 CREATED BY	  : VENKAT CHAITANYA KANUMUKULA 
 CREATED ON	  : This is created and tested in SQL SERVER 2000 and SQL SERVER 2005.
 PURPOSE      : This Object is Created for exporting a Stored Procedure results into a new Table Name(StoredProcedureName+_Report).
 COMMENTS     : The Below Proc can handle any number of parameters.
				Tested on SQL Server 8.00.194 - RTM (Desktop Engine) ,SQL Server 9.00.4035.00 - SP3 (Developer Edition)
 MODIFIED BY  : VENKAT CHAITANYA KANUMUKULA 
 EXAMPLE 1	  : exec [XportStoredProc]  'StoredProcedureName 2,2' ( 2 Integer Params)
 EXAMPLE 2	  : exec [XportStoredProc]  'StoredProcedureName 1,1,''''Test''''' ( Integer and Varchar Params)
 EXAMPLE 3	  : exec [XportStoredProc]   StoredProcedureName    OR
				exec [XportStoredProc]  'StoredProcedureName'
			    This object can accept 'n' Number of Parameters.
 **********************************************************************/
 
DECLARE @vsSQL nvarchar(4000)
DECLARE @SQL nvarchar(4000)
DECLARE @vsServerName varchar(50) 
DECLARE @vsSPName varchar(100) 
DECLARE @vsDestDBName varchar(100) 
DECLARE @vsDestTableName varchar(100) 
DECLARE @CRLF char(2)
SET @CRLF = char(10)

-- If @SRCOBJECT does not have Parameter then to handle it
SELECT @SRCOBJECT = @SRCOBJECT + ' '
SELECT @vsServerName = '[' + Convert(VARCHAR,SERVERPROPERTY ('ServerName') ) + ']'
SELECT @vsSPName =  Convert(VARCHAR,db_name()) + '.' + @SCHEMA + '.' + @SRCOBJECT 
SELECT @vsDestTableName = Convert(VARCHAR,db_name()) + '.' + @SCHEMA + '.' +(SUBSTRING(@SRCOBJECT+'_Report',1, PATINDEX('% %', @SRCOBJECT +'_Report')-1))+'_Report'

BEGIN
-- This will drop table if exists and recreates it with the extension ProcedureName + '_Report'
-- Tested and Executed.
SELECT @vsSQL = '
IF  EXISTS (SELECT * FROM sysobjects WHERE name = (N'''+(SUBSTRING(@SRCOBJECT+'_Report',1, PATINDEX('% %', @SRCOBJECT +'_Report')-1))+'_Report'+ ''') AND xtype = (N''U''))
DROP TABLE [dbo].['+(SUBSTRING(@SRCOBJECT+'_Report',1, PATINDEX('% %', @SRCOBJECT +'_Report')-1))+'_Report]'+@CRLF+'
  SELECT * INTO '  +  @vsDestTableName  +  ' FROM OPENQUERY ' + '(' + @vsServerName + ','
SELECT @vsSQL = @vsSQL + '''SET FMTONLY OFF  EXECUTE ' +  @vsSPName  + '' 
SELECT @SQL = SUBSTRING(@vsSQL,1,LEN(@vsSQL)) + ''')'

DECLARE @Server VARCHAR(50) 
SET @Server = @@SERVERNAME 
-- This ServerOption Should be Turned on to use the OPENQUERY function.
EXEC sp_serveroption  @Server,'DATA ACCESS','TRUE' 
--PRINT @SQL
EXEC sp_executeSQL @SQL
-- ServerOption Turned off
EXEC sp_serveroption  @Server,'DATA ACCESS','FALSE'
 
END

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
United States United States
Mr. Kanumukula is a IT-Professional and has been in the industry since 1997.
• Around 15+ years of experience in the areas of system design & architecture, application programming, development, testing, deployments, execution with implementations & Roll-outs of business applications in cloud/on-premise.
• Experience with Dynamics 365 for F&O/Dynamics AX, D365 for Business Central/NAV,(Inc -Visual Studio.Net, X++, AL, C#, CSide, SharePoint, SQLServer, SFDC, Power-BI, Power Apps, Dataverse/Common Data Service, CRM, SSIS/SSRS/SSAS, BizTalk, IOT, IIOT, JAVA, AWS, GCP, Azure, API, etc)
• Experience in managing Operations & Data Center maintenance both on-premise & cloud hosting, infrastructure/applications assessments & build systems.
• Experience in ERP upgrades, Mulesoft API's,MS Dynamics 365,Azure administration & hosting, LCS-Life Cycle Services.
• Experience with Commitment to Quality, technical quality assurance(before, during & after development). Create partnership with project manager to give technical assistance regarding important decisions.
• Well-Versed with Agile, SCRUM & CMMI process & methodologies to support rapid iterative Quality software development.

A highly motivated, self-starter & problem solver with multi-tasking skills, Had managed and served through an established process to get the job done in a timely and efficient manner with an eye on every detail during ERP-implementations. Flexible to work under stress and have ability to prioritize workload and stay organized in a fast-paced environment.

Learned & adapted to new technologies & tools at ease, aggressively delivered tasks on-demand at a fast-pace satisfying the needs of product owners, product development, program managers, Vendors, Higher Management, Internal/External Clients.

Have a proactive & positive attitude with a willingness to do what it takes to complete the job. Self-managed work style within a team environment. Extremely detail & Customer service oriented.

Comments and Discussions