我想从数据库中已经存在的所有表中创建视图,这是逐个捕获表的艰巨任务,并使得创建视图XXXX作为select * from Table_name。我发现可以使用游标并且代码是:
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
但它有错误,我不知道如何解决它
答案 0 :(得分:3)
这是我对动态SQL的处理方式;首先检查视图是否存在,然后使用所有列创建它(而不是使用SELECT * FROM...
)。
DECLARE @SQL nvarchar(MAX)
SET @SQL = N''
SELECT
@SQL = @SQL +
N'IF EXISTS(SELECT 1 FROM sys.objects WHERE name = N''v_' + t.name + N''' AND type = N''V'') BEGIN DROP VIEW [v_' + t.name + '] END CREATE VIEW [v_' + t.name + N'] AS SELECT ' +
STUFF(
(SELECT N',' + c.name
FROM
sys.columns AS c
WHERE
c.OBJECT_ID = t.OBJECT_ID
ORDER BY
column_id
FOR XML PATH(''), TYPE).value('.',N'nvarchar(max)')
,1,1,N'')
+ N' FROM [' + t.name + N'];'
FROM
sys.tables AS t
EXEC sp_executesql @SQL