我编写了以下代码来填充/创建数据库中所有相应视图(t_
)的表(v_
)。我使用游标转换了以前的脚本以提高运行速度。还有什么我可以做的让这个表现更好吗?
感谢任何帮助。
请参阅我的代码:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[P_populate_tables_from_views]
@dropTables BIT
AS
DECLARE @viewName NVARCHAR(100);
DECLARE @formattedTableName NVARCHAR(100);
DECLARE @dropTableSql NVARCHAR(MAX);
DECLARE @viewId int
SET @viewId = (SELECT MIN(object_id) FROM sys.views)
WHILE @viewId IS NOT NULL
BEGIN
SET @viewName = (SELECT name FROM sys.views WHERE object_id = @viewId)
PRINT 'Time: ' + CONVERT(varchar, SYSDATETIME(), 121)
PRINT('Processing ' + @viewName)
SET @formattedTableName = REPLACE(@viewName,'v_','t_');
IF @dropTables = 1
BEGIN
SET @dropTableSql = 'IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '''+@formattedTableName+''')) DROP TABLE '+@formattedTableName
EXEC (@dropTableSql);
END
IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @formattedTableName))
BEGIN
EXEC('TRUNCATE TABLE '+@formattedTableName)
EXEC('INSERT INTO '+@formattedTableName +' SELECT * FROM '+ @viewName)
END
ELSE
BEGIN
EXEC ('SELECT * INTO '+@formattedTableName+' FROM '+@viewName);
END
SET @viewId = (SELECT MIN(object_id)
FROM sys.views
WHERE object_id > @viewId)
END
答案 0 :(得分:0)