我有以下查询:
select top 10 'CISPRO_THXCOCD_201906' as tablename,* from HXCOCD_201906
select top 10 'CISPRO_THXCOCL_201906' as tablename,* from HXCOCL_201906
select top 10 'CISPRO_THXICLD_201906' as tablename,* from HXICLD_201906
select top 10 'CISPRO_THXICLM_201906' as tablename,* from HXICLM_201906
select top 10 'CISPRO_THXICND_201906' as tablename,* from HXICND_201906
select top 10 'CISPRO_THXINXT_201906' as tablename,* from HXINXT_201906
查询目的是提供给定表中的示例数据
我有差不多50个以上的查询;有什么方法可以将结果合并为一个结果集?
问题在于每个表具有不同的列名,并且列数也不同。
据我所知,我想分别运行每个查询并将其粘贴到Excel工作表中。
是否有比批量运行更简单的方法来批量运行查询?
答案 0 :(得分:2)
您可以为最终结果集定义结构,并为每个表的缺失列提供默认值。
SELECT TOP 10
COL1, COL2, COL3, 0 AS COL4, COL5
FROM
HXCOCD_201906
UNION
SELECT TOP 10
COL1, COL2, NULL AS COL3, COL4, 0 AS COL5
FROM
HXCOCL_201906
UNION
....
答案 1 :(得分:0)
这会将结果保存到csv,因此可能无法满足您的需求。
步骤如下:
配置用于文本输出的查询结果:查询->查询选项->结果->文本(请参见屏幕截图)
没有标题,结果状态的单独标签,您选择的自定义分隔符
设置结果以输出到txt
示例:
--Temp table to hold list of tables
CREATE TABLE #tbls (tblname varchar(20))
--Add all tables to table list
INSERT INTO #tbls (tblname)
SELECT '1'
UNION ALL SELECT '2'
UNION ALL SELECT '3'
UNION ALL SELECT '4'
UNION ALL SELECT '5'
--Create cursor
DECLARE tblcur CURSOR
FOR SELECT tblname FROM #tbls
OPEN tblcur
DECLARE @tblname varchar(20)
DECLARE @sql nvarchar(max) = ''
FETCH NEXT FROM tblcur
INTO @tblname
--Output contents of tables
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = @SQL + 'SELECT ['+ @tblname + '_ID] AS tablename,* FROM dbo.[' + @tblname +']'
execute sp_executesql @SQL
FETCH NEXT FROM tblcur
INTO @tblname
END
CLOSE tblcur
DEALLOCATE tblcur
DROP TABLE #tbls