我有许多表,我想根据视图动态创建和填充。
我想执行类似这两个帖子的组合:
有没有办法在不使用游标的情况下循环遍历 TSQL 中的表变量?
Select *
Into dbo.##tblTemp
From databasename.sys.views
Declare @TableName NVARCHAR(128)
While (Select COUNT(*) From #Temp) > 0
Begin
Select Top 1 @TableName = name from databasename.sys.views
Select * into @TableName from databasename.sys.views
Delete databasename.sys.views Where name = @TableName
End
我最好使用动态创建 sql 语句来创建表的存储过程吗?
编辑:
根据 Sebastian,我正在运行以下代码来完成此操作:
DECLARE @cmd NVARCHAR(MAX) = ( SELECT TOP 10 'exec sp_rename '
+ '@objname =''' + OBJECT_SCHEMA_NAME(object_id)
+ '.'
+ OBJECT_NAME(object_id) + ''
+ ''', @newname = '
+ '''v_' + name + ''
+ ''';'
+ 'SELECT * INTO '
+ OBJECT_SCHEMA_NAME(object_id)
+ '.'
+ OBJECT_NAME(object_id)
+ ' FROM '
+ OBJECT_SCHEMA_NAME(object_id)
+ '.v_'
+ OBJECT_NAME(object_id)
+ ';'
+ 'DROP VIEW '
+ OBJECT_SCHEMA_NAME(object_id)
+ '.v_'
+ OBJECT_NAME(object_id)
+ ';'
FROM db.sys.views
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)');
EXEC (@cmd)
--选择@cmd