Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 SP to retrieve data from more then one Table

Author  Topic 

Sedanda
Starting Member

13 Posts

Posted - 2010-09-16 : 03:15:37
Hi Forum,
I have an SP that uses a table to retrive data from many tables.


SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
Alter Procedure [dbo].[Fetch_Table_Data]
AS
Begin
-- Declare the variables to store the values returned by FETCH.
DECLARE @Table varchar(8000);
declare @cmd varchar (8000);
set @cmd = ''
DECLARE Table_cursor CURSOR FOR
SELECT distinct ProjektTabelle
FROM dbo.T_TProjekte;

OPEN Table_cursor;
-- Perform the first fetch and store the values in variables.
-- Note: The variables are in the same order as the columns
-- in the SELECT statement.
FETCH NEXT FROM Table_cursor
INTO @Table;

-- Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE @@FETCH_STATUS = 0
BEGIN
-- Concatenate and display the current values in the variables.
if @cmd <> ''
set @cmd = @cmd + ' union '
set @cmd = @cmd + 'Select CNI,CPROJEKT from ' + @Table
-- This is executed as long as the previous fetch succeeds.
FETCH NEXT FROM Table_cursor
INTO @Table
exec(@cmd)
END
CLOSE Table_cursor
DEALLOCATE Table_cursor
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO


My problem is that it runs every select one after the other so is there any way to first build the complete string with a Union for all the tables before it runs the select?
Jeff

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-09-16 : 03:26:18
Put the exec(@cmd) one line down (after the END of the WHILE loop.


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

Sedanda
Starting Member

13 Posts

Posted - 2010-09-16 : 03:48:08
Thanks Webfred.
Go to Top of Page
   

- Advertisement -