我有一个主表,其中包含与该表对应的表名和列。
我想编写一个迭代表的所有记录并获取所有数据并将其作为单个结果集返回的过程。
答案 0 :(得分:0)
您需要使用Dynamic Query
DECLARE @sql VARCHAR(max)=''
SET @sql = (SELECT @sql + 'select ' + column_name + ' from '
+ table_name + ' union all '
FROM master_table
FOR xml path(''))
SELECT @sql = LEFT(@sql, Len(@sql) - 9)
EXEC (@sql)
注意:所有列的数据类型应相同。如果不是这种情况,那么您可能必须明确转换为varchar
SET @sql = (SELECT @sql + 'select cast(' + column_name + ' as varchar(4000)) from '
+ table_name
+ ' union all '
FROM Master_table
FOR xml path(''))
答案 1 :(得分:0)
假设Master表中列出的所有表具有相同的列和相同的订单和数据类型。然后它将如下:
create table ##a
(
Value int
)
create table ##b
(
Value int
)
create table ##c
(
Value int
)
declare @all table
(
Value int
)
declare @master table
(
TableName varchar(10)
)
declare @TableName varchar(10)
insert ##a values (1), (2), (3)
insert ##b values (4), (5), (6)
insert ##c values (7), (8), (9)
insert @master values ('##a'), ('##b'),('##c')
declare looper cursor local static forward_only read_only for
select TableName from @master
open looper
fetch next from looper into @TableName
while @@fetch_status = 0
begin
insert @all exec('select Value from ' + @TableName)
fetch next from looper into @TableName
end
close looper
deallocate looper
select * from @all
drop table ##a
drop table ##b
drop table ##c
如果表格结构不同,请访问Stored procedures and multiple result sets in T-SQL。它会将每个表的内容压缩到一个XML单元中。文章还解释了如何阅读它们。
答案 2 :(得分:0)
我假设您在主表中使用了许多具有不同列的表。你应该循环你的主表。试试这样,
DECLARE @sql NVARCHAR(max) = ''
DECLARE @start INT = 1
,@end INT = 0
,@tablename VARCHAR(100) = ''
DECLARE @TableList TABLE (
id INT identity(1, 1)
,tablename VARCHAR(128)
)
INSERT INTO @TableList (tablename)
SELECT DISTINCT table_name
FROM YourMasterTableName
WHERE TABLE_NAME = 'productss'
SET @end = @@ROWCOUNT
WHILE (@start <= @end)
BEGIN
SET @tablename = (
SELECT tablename
FROM @TableList
WHERE id = @start
)
SET @sql = (
SELECT ',[' + column_name + ']'
FROM YourMasterTableName M
WHERE TABLE_NAME = @tablename
FOR XML path('')
)
SET @sql = 'SELECT ' + stuff(@sql, 1, 1, '') + ' FROM ' + @tablename
EXEC sp_executesql @sql
SET @start = @start + 1
END