Domanda

I'm currently working on an sql task and I need help on the query. So basically, I'm trying to loop through several tables, with similar columns (though with different data in it).

I did so by passing through a string of the table names with commas as the delimiter. Then I split the string using the function [dbo].[ufn_tbSplit] which then return a temp table with a column called 'Token' that stored the tables' names.

So, here, I use cursor to loop through each table. No problem there. But the problem come when I want to loop the + ' UNION SELECT DISTINCT [Die_X_Position], [Die_Y_Position] FROM ' statement. If I only have 2 tables, then it will be no problem. But what if I have around 5 tables? I want to loop the union statement so that it will include all the other tables as well. How can I achieve this? I'm currently using MS SQL Server 2008 R2. Thanks!

DECLARE C1 CURSOR FOR SELECT Token FROM [dbo].[ufn_tbSplit](@TableString_IN, ',')
OPEN C1
FETCH next FROM C1 INTO @TempTable
WHILE @@FETCH_STATUS <> -1
BEGIN
    SET @xDie1 = @TempTable 
    FETCH next FROM C1 INTO @TempTable 
    SET @xDie2 = @TempTable
    SET @xDie = 'SELECT DISTINCT [Die_X_Position], [Die_Y_Position] FROM ' + @xDie1
                + ' UNION SELECT DISTINCT [Die_X_Position], [Die_Y_Position] FROM ' + @xDie2 
    EXEC sp_executesql @xDie
    FETCH next FROM C1 INTO @TempTable
END
CLOSE c1
DEALLOCATE c1
È stato utile?

Soluzione

This should have what you need.

DECLARE @sql varchar(max)
set @sql = ''
DECLARE @sqlTemplate varchar(max)
set @sqlTemplate = ' SELECT DISTINCT [Die_X_Position], [Die_Y_Position] FROM '
DECLARE @i int
set @i = 0
DECLARE C1 CURSOR FOR SELECT Token FROM [dbo].[ufn_tbSplit](@TableString_IN, ',')
OPEN C1
FETCH next FROM C1 INTO @TempTable
WHILE @@FETCH_STATUS <> -1
BEGIN
    if @i <> 0
    begin
      set @sql = @sql + ' UNION ' + @sqlTemplate + @TempTable
    end
    else
    begin
      set @sql = @sqlTemplate + @TempTable
    end
    set @i = @i + 1
    FETCH next FROM C1 INTO @TempTable
END
EXEC sp_executesql @sql
CLOSE c1
DEALLOCATE c1
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top