0

我正在寻找一种方法来1:1为一堆表自动创建每个表的视图。由于我需要查看大量表,因此手动创建它们会很耗时。

完美的场景将是一个查询,create view为一次给定的每个表创建查询。

4

2 回答 2

2

这应该可以解决当前数据库的问题。它仍然是动态 SQL,但是……请注意,它不会检查视图是否已经存在。您可以WHERE向游标查询添加子句以限制表 -WHERE t.name = '...'WHERE t.name IN ('...','....').

DECLARE @TableName sysname
DECLARE @ColumnCount INT
DECLARE @ColumnID INT
DECLARE @SelectColumn NVARCHAR(500)
DECLARE @sql NVARCHAR(max) = ''

DECLARE QUERYINFO CURSOR FOR
    SELECT
        t.name AS TableName,
        ccount.ColumnCount,
        c.column_id AS ColumnID,
        CASE WHEN c.column_id <> ccount.ColumnCount
                THEN c.name + ', '
             ELSE c.name
             END AS SelectColumn
    FROM sys.tables t
    INNER JOIN sys.columns c ON t.object_id=c.object_id
    INNER JOIN (
        SELECT object_id,COUNT(*) AS ColumnCount
        FROM sys.columns
        GROUP BY object_id
    ) ccount ON t.object_id = ccount.object_id
    ORDER BY t.Name,c.column_id

OPEN QUERYINFO
FETCH NEXT FROM QUERYINFO INTO @TableName,@ColumnCount,@ColumnID,@SelectColumn
WHILE @@FETCH_STATUS = 0
BEGIN
    IF @ColumnID = 1
    BEGIN
        SET @sql = 'CREATE VIEW v_' + @TableName + ' AS SELECT ' + @SelectColumn
    END
    ELSE
    BEGIN
        SET @sql = @sql + @SelectColumn
    END  

    IF @ColumnID = @ColumnCount
    BEGIN
        SET @sql = @sql + ' FROM ' + @TableName
        EXEC sys.sp_executesql @sql
        SET @sql = ''
    END 

    FETCH NEXT FROM QUERYINFO INTO @TableName,@ColumnCount,@ColumnID,@SelectColumn
END

CLOSE QUERYINFO
DEALLOCATE QUERYINFO
于 2013-01-09T15:53:19.847 回答
0

我知道这有点过时,但您可以使用带有递归 CTE 的临时表将 sys.columns 和 sys.tables 中的列串在一起,然后在不使用过程或游标的情况下构建视图。这是一个例子。这个只选择一个object_id,但您可以为数据库中的所有表运行它。唯一的问题可能是您的表是否大于 100 列。我认为 CTE 的默认深度是 100 个递归连接。

SELECT t.name AS TableName
        , ccount.ROW_COUNT
        , c.column_id AS ROW_RANK
        , c.name as COL

INTO #VT_TEMP

FROM sys.tables t  INNER JOIN sys.columns c 
ON t.object_id=c.object_id

INNER JOIN (  SELECT  object_id
                    , COUNT(*) AS ROW_COUNT
               FROM sys.columns
               GROUP BY object_id
    ) ccount 
ON t.object_id = ccount.object_id
WHERE t.OBJECT_ID = 245575913
ORDER BY t.Name, c.COLUMN_ID
;



WITH MYVIEW_CTE  ( T_NAME, R_COUNT, R_RANK, TXT )

AS 
  (
    SELECT TABLENAME
         , ROW_COUNT
         , ROW_RANK
         , CAST(COL AS VARCHAR(MAX))

    FROM #VT_TEMP 
    WHERE ROW_RANK = 1

    UNION ALL

    SELECT  V.TABLENAME
          , V.ROW_COUNT 
          , V.ROW_RANK
          , CAST(TXT  + ', ' +  V.COL AS VARCHAR(MAX)) 


    FROM #VT_TEMP V INNER JOIN MYVIEW_CTE C
    ON  V.TABLENAME = T_NAME
    AND V.ROW_RANK = R_RANK + 1
 )  

 SELECT CC.T_NAME
        ,CC.TXT
        , 'CREATE VIEW V_' + CC.T_NAME + ' AS SELECT ' + CC.TXT + ' FROM dbo.' + CC.T_NAME + ' ;' as DDL_View
 FROM MYVIEW_CTE CC INNER JOIN (

 SELECT T_NAME, MAX(R_RANK) AS MX_CNT
 FROM MYVIEW_CTE C
 GROUP BY T_NAME
 ) SC
 ON CC.T_NAME = SC.T_NAME
 AND CC.R_RANK = SC.MX_CNT
于 2015-12-03T16:35:00.617 回答