[英]SQL Server 2008: populate a table with data from dynamic table
I have two tables Control1 (BatchID ,TableName)
, Control2(BatchID, MemID)
and there are additional tables that will be added to the database one by one. 我有两个表Control1 (BatchID ,TableName)
和Control2(BatchID, MemID)
并且还有其他表将被一张一张地添加到数据库中。 The format for the tablename is ABC_date
for example ABC_01032014
(dynamic) 表名的格式为ABC_date
,例如ABC_01032014
(动态)
Now this Table ABC_Date has one caolumn Called MemID
. 现在,此表ABC_Date具有一个称为MemID
。
control1
and control2
are empty tables and abc_date
is populated with let's say 10 MemIds
. control1
和control2
是空表和abc_date
填充了比方说10 MemIds
。
So, I want to populate control1
and control2
. 所以,我想填充control1
和control2
。 Control1
would have a unique ID and tableName = ABC_date
DONE Control1
将具有唯一的ID,并且tableName = ABC_date
DONE
control2
would have the same BatchID
as control1
and all 10 memIds
from ABC_Date
. control2
将具有相同的BatchID
为control1
,所有10 memIds
从ABC_Date
。 Please help with control2
. 请帮助control2
。
Now it should have all 10 memIDs
from ABC_Date
and 1 same batchID
from control1
现在它应该具有来自ABC_Date
所有10 memIDs
ABC_Date
和来自control1
1个相同的batchID
Thanks 谢谢
I'm not sure if you want 10 rows in control 2 or just one with the MemIDs separated by a comma but I'm assuming you want 10 registers 我不确定您是否要在控件2中使用10行,还是只希望其中的一行用逗号分隔MemID,但我假设您要使用10个寄存器
you could use a cursor to do the job for you 您可以使用光标为您完成工作
Declare @BatchID
Declare @MemIdFetch
Set @BatchID = Select distinct BatchID from control1
--Declaration of the cursor
Declare CursorABC cursor for select MemID from ABC_date where BatchID = @BatchID
--Fetching the cursor
Fetch CursorABC into @MemIdFetch
--Loop for the cursor
WHILE(@@FETCH_STATUS = 0)
BEGIN
insert into control2 select @BatchID,@MemIdFetch
Fetch CursorABC into @MemIdFetch
END
Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.