2011-07-05 72 views
0

我有如下表:構建在運行時選擇語句並執行使用sp_MSforeachtable

ID TableName FieldName 
1 tbl1 fieldA 
1 tbl1 fieldB 
2 tbl2 fieldC 
2 tbl2 fieldD 

的DDL是在

Declare @tblPlaceholder table(ID int,TableName Nvarchar(20),FieldName Nvarchar(20)) 
insert into @tblPlaceholder 
    select 1,'tbl1','fieldA' union all select 1,'tbl1','fieldB' union all 
    select 2,'tbl2','fieldC' union all select 2,'tbl2','fieldD' 
select * from @tblPlaceholder 

我需要做的是,在運行時我需要用字段和表名構建查詢,從此我需要執行它們。

所以,在運行時將要形成的查詢是

ID Query 
1 Select tbl1.fieldA,tbl1.fieldB from tbl1 
2 Select tbl2.fieldC,tbl2.fieldD from tbl2 

我的查詢是在偉大工程

-- Step 1: Build the query and insert the same into a table variable 
Insert into @t 
Select ID, Query = ' Select ' + FieldNames + ' from ' + TableName 
From 
(
Select ID,TableName, FieldNames = Stuff((select ',' + CAST(TableName as Nvarchar(20)) + '.' + CAST(FieldName as Nvarchar(20)) 
      from @tblPlaceholder t2 where t2.ID = t1.ID 
      FOR XML PATH('')),1,1,'') 
From @tblPlaceholder t1 
Group By t1.ID,t1.TableName)X 

/* output of step 1 
select * from @t 

ID Query 
1 Select tbl1.fieldA,tbl1.fieldB from tbl1 
2 Select tbl2.fieldC,tbl2.fieldD from tbl2 
*/ 


-- Step 2 : loop thru the ID and execute the queries 
While (@i <= 2) -- since there are two id's.. this can even be configurable as max(id) 
Begin 
     SELECT @QueryList = (Select Query from @t where ID = @i) 
     exec(@QueryList)  
     set @i += 1 
End 

但我敢肯定,這是可以做到即使在一個更好的方法。我正在尋找sp_MSforeachtable但我不確定我們是否可以這樣做?

請問你們能否幫助我。

+1

除非@tblPlaceholder包含每個表中的一行,併爲每個表中的所有列,sp_MSforeachtable不作一大堆的意義 - 它曾經執行給定的命令爲數據庫中的每個用戶表,並且沒有按不符合你的代碼看起來在做什麼。 –

回答

0

我做了一個例子。調整它以符合您的需求。

DECLARE @mytable AS VARCHAR(100) 
DECLARE @sql AS VARCHAR(1000) 

     DECLARE mycursor CURSOR FOR 
     SELECT name 
     FROM sys.tables 
     -- WHERE your conditions here! 

     OPEN mycursor 
     FETCH NEXT FROM mycursor INTO @mytable 

     WHILE @@FETCH_STATUS = 0 

     BEGIN 

     SET @sql = 'SELECT * FROM ' + @tablename -- Define the query string. replace with your code 
     EXEC(@sql) -- execure the query 
     FETCH NEXT FROM mycursor INTO @mytable 

     END 

     CLOSE mycursor 
     DEALLOCATE mycursor 
相關問題