我正在寻找一种方法来为一堆表自动创建每个表的1:1
视图。
由于我需要查看大量的表,因此手动创建它们会非常耗时。
完美的方案是为一次创建的每个表创建 create view
查询的查询。
答案 0 :(得分:1)
这应该可以解决当前数据库的问题。它仍然是动态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
答案 1 :(得分: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