使用sysobjects表中的表名创建Sql Server视图

时间:2016-06-22 05:39:54

标签: sql sql-server view sql-server-2012

我有大约200张桌子。我想从所有这些表中创建一个view。我觉得硬编码所有表名并在视图定义中执行UNION ALL效率很低。

相反,我打算从sysobjects表中检索表名,如

 Select name from sysobjects where name like 'Warehouse_Inventory%'

如何使用这些表名并从中创建view

注意:我只选择10列常见的列。如果表中没有任何列,我想为它显示NULL。

2 个答案:

答案 0 :(得分:0)

此查询可以帮助您..

    SELECT 'CREATE VIEW VIEW_NAME AS'
    UNION ALL
    SELECT 'SELECT * FROM ['+NAME+']
    UNION ALL' FROM SYS.TABLES where name like 'Warehouse_Inventory%'

答案 1 :(得分:0)

我不确定为什么要使用sys.sysojects而不是其他sys视图。现在也确定为什么当你想要联合所有表格时你想用表名搜索.....我可能会推荐一个表格和临时表上的游标来保存你的结果如果你有200个表只是做大小的查询,但如果你真的真的想通过联盟来做所有这里是一种方式......

构建所需的10列的列表。然后运行查询。您可能需要调整并添加一些转换/转换函数以确保一切都是正确的数据类型,这可以使用sys.types和sys.columns动态完成,或者通过更改我的动态sql确保一切都是NVARCHAR(???)在下面继续前进。

DECLARE @ListOfColumns AS TABLE (ColumnName VARCHAR(100))
INSERT INTO @ListOfColumns (ColumnName) VALUES ('col1'),('col2'),('col3')

DECLARE @SQLStatement NVARCHAR(MAX)

;WITH cteColumnsTableCross AS (
    SELECT
       SchemaName = s.name
       ,t.schema_id
       ,TableName = t.name
       ,l.ColumnName
    FROm
       @ListOfColumns l
       CROSS JOIN sys.tables t
       INNER JOIN sys.schemas s
       ON t.schema_id = s.schema_id
)


, cteColumns AS (
    SELECT
       x.SchemaName
       ,x.TableName
       ,x.ColumnName
       ,ColumnExists = IIF(c.name IS NOT NULL,1,0)
       ,RowNum = ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY x.TableName DESC)
       --you can add data type by getting from sys.columns and sys.types if desired
    FROM
       cteColumnsTableCross x
       LEFT JOIN sys.tables t
       ON x.TableName = t.name
       AND x.schema_id = t.schema_id
       LEFT JOIN sys.columns c
       ON t.object_id = c.object_id
       AND x.ColumnName = c.name
)

, cteSelectStatements AS (
    SELECT
       TableName = t.name
        ,TableSelect = 'SELECT TableName = ''' + t.name +  ''', ' + 

            STUFF(
            (SELECT ', ' + c.ColumnName + ' = ' + IIF(c.ColumnExists = 0,'NULL',c.ColumnName)
            FROM
                cteColumns c
            WHERE t.name = c.Tablename
            FOR XML PATH(''))
            ,1,1,'')

          + ' FROM ' + t.name + 

          IIF((ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY t.name DESC)) > 1,' UNION ALL ','')
    FROM
       sys.tables t
)

SELECT @SQLStatement = STUFF(
        (SELECT ' ' + TableSelect
        FROM
            cteSelectStatements
       ORDER BY
          TableName
        FOR XML PATH(''))

        ,1,1,'')

PRINT @SQLStatement
--EXECUTE @SQLStatement