0
を使用して実行します。は、私は以下の表を持って、実行時にSelectステートメントを構築し、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を探していましたが、私たちがそうすることができるかどうかわかりませんか?
あなたは私を助けてください。
、sp_MSforeachtableは意味の全体の多くを作成しません。あなたのコードがやっているように見えます。 –