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.
| 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 GOSET ANSI_NULLS ON GOAlter Procedure [dbo].[Fetch_Table_Data]ASBegin-- Declare the variables to store the values returned by FETCH.DECLARE @Table varchar(8000);declare @cmd varchar (8000);set @cmd = ''DECLARE Table_cursor CURSOR FORSELECT distinct ProjektTabelleFROM 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_cursorINTO @Table;-- Check @@FETCH_STATUS to see if there are any more rows to fetch.WHILE @@FETCH_STATUS = 0BEGIN-- 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 @Tableexec(@cmd)ENDCLOSE Table_cursorDEALLOCATE Table_cursorENDGOSET QUOTED_IDENTIFIER OFF GOSET 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. |
 |
|
|
Sedanda
Starting Member
13 Posts |
Posted - 2010-09-16 : 03:48:08
|
| Thanks Webfred. |
 |
|
|
|
|
|