2012-06-04 82 views
2

我需要在表名後綴是從另一個表,這樣,從表中選擇:查詢多個表中TSQL,其中表名來自另一個表

declare @value nvarchar(3), 
@table nvarchar(1000), 
@SQLST NVARCHAR(255); 

set @value = N'select column1 from tableX'; 

EXEC @value 

set @table ='partoftableY' 

Set @SQLST ='select * from' [email protected] + @value -- here I create the table name 

但也有在TableX的(多個值0-999),所以這是行不通的。我需要一個For Each類型結構嗎?

+1

有兩種方式做到這一點 - 你可能不需要做的for-each(稱爲一個遊標) - 它可能在有可能一套操作。請告訴我們您的結果,我們會看到最好的解決方案。 –

+0

嗨,最後我需要將所有表格合併爲一個。例如:結果將是十個表格 – user1434979

回答

1

在這裏我有兩個表(partoftableY1 & partoftableY2)具有不同的數據在每個

/* 

create table tableX (column1 int); 

insert into tablex 
      select 1 
union all select 2; 

create table partoftableY1 (data nvarchar(50)); 
create table partoftableY2 (data nvarchar(50)); 

insert into partoftableY1 select 'hey 1 here'; 
insert into partoftableY2 select 'hey 2 here'; 

*/ 


declare @sql nvarchar(max) 

-- use the ability of SQL to build up string of all the sql you need to run 

set @sql = 'select data from (select '''' as data' 

select @sql = COALESCE(@sql + ' union all ', '') 
       + 'select data from partoftableY' 
       + cast(column1 as nvarchar(4)) from tableX 
select @sql = @sql + ') X where data <>''''' 

-- DEBUG for seeing what SQL you created 
print @sql 

-- Now execute the SQL 
exec sp_executesql @sql= @sql 

創建了一個例子,給了我的

hey 1 here 
hey 2 here 

結果,您將需要調整它爲您的數據類型,但這應該給你的主要想法

For re這裏是創建和執行的sql:

select data 
from (
       select '' as data 
     union all select data from partoftableY1 
     union all select data from partoftableY2 
    ) X 
where data <>'' 

N.B.

  • 我把格式化它更容易閱讀,因爲它是作爲一個長線
  • 我用selet數據,而不是選擇*爲列數必須在工會的每個相同的選擇實際創建。您將需要選擇所需的列,然後進行更改以確保聯合中選擇的所有列都相同。
  • 在工會的頂部有一個虛擬選擇,以使工會代碼更容易 - 不需要條件,因爲工會是否需要提供
  • 我用out select來覆蓋整個工會,使您能夠獲得sid假人的選擇
+0

謝謝:)我想我得到了想法。結果(所有存在的表格)將全部在一個表中加入。 – user1434979

+0

是的,但你需要小心,並把檢查代碼,以確保你避免表ex前重複。還有其他的錯誤,如tablex中的數據,但其他表不存在等。 –

+0

其他的事情,你是什麼意思的數據?要選擇的列?謝謝 – user1434979

0

你可以試試這個

DECLARE @SQLST NVARCHAR(max)=''; 

DECLARE @select nvarchar(max)=N'select * from partoftableY' 

DECLARE @union nvarchar(max)=N' 
UNION ALL 
' 
SELECT @[email protected][email protected] 
FROM tablex 

SELECT @SQLST=substring(@SQLST,1,LEN(@SQLST)-11) 

EXEC sp_executesql @SQLST 
+0

partoftableY是表格示例的一部分:有多個表,如customerY,custormerX,customerZ,customerA。所以我試圖搜索customer + @a,其中@a包含(Y,Z,X,A),而這個@a是從其他表(名稱) – user1434979

相關問題