I have a stored procedure that selects some data in a different format from my original table:
USE [VolTracker]
GO
DECLARE @return_value int,
@offset int
SET @offset = 5
WHILE @offset >= 1 BEGIN
EXEC @return_value = [dbo].[sp_getStats]
@Doffset = @offset,
@StartTime = --Some Datetime,
@EndTime = --Some later Datetime,
@Contract = NULL
SET @offset = @offset - 1
END
GO
This specific example selects all 5 of the tables that I would like it to properly. However, I would like all of these tables joined into one table. How might I go about doing this?
Create a temporary table or table variable and insert into table each time you execute the stored procedure. Check this out.
//declare your #temptable here
WHILE @offset >= 1 BEGIN
INSERT INTO #tempTable
EXEC @return_value = [dbo].[sp_getStats]
@Doffset = @offset,
@StartTime = --Some Datetime,
@EndTime = --Some later Datetime,
@Contract = NULL
SET @offset = @offset - 1
END
Create a table variable that matches the schema of the resultset returned by sp_getStats. Then, insert into this variable within your loop:
...
declare @Stage table (YourColumn1 varchar(10), YourColumn2 int, ...);
WHILE @offset >= 1 BEGIN
INSERT INTO @Stage
EXEC @return_value = [dbo].[sp_getStats]
@Doffset = @offset,
@StartTime = --Some Datetime,
@EndTime = --Some later Datetime,
@Contract = NULL
SET @offset = @offset - 1
END
select * from @Stage;
The above will work to return the union of all the resultsets returned, however if its possible for you to modify the procedure (or create a new one) that can return the complete set without a loop then I would suggest doing do.
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.