如何批量更新SQL模式

时间:2017-09-04 19:03:35

标签: sql sql-server database tsql database-schema

我正在尝试更新所有表,过程和视图的特定模式;但是,我收到了权限错误,我已经尝试了所有内容。

有人可以通过正确的方式帮助显示以下查询的权限,以便不会收到以下错误。

查询

    USE CAD

DECLARE @OldSchema VARCHAR(200)
DECLARE @NewSchema VARCHAR(200)
DECLARE @SQL nvarchar(4000)
SET @OldSchema = 'Storefront'
SET @NewSchema = 'CadType'

DECLARE tableCursor CURSOR FAST_FORWARD FOR 
    SELECT 'ALTER SCHEMA  ['+ @OldSchema +'] TRANSFER [' + @NewSchema + '].[' + DbObjects.Name + '];' AS Cmd
    FROM sys.Objects DbObjects
    INNER JOIN sys.Schemas SysSchemas ON DbObjects.schema_id = SysSchemas.schema_id
    WHERE SysSchemas.Name = @OldSchema
    AND (DbObjects.Type IN ('U', 'P', 'V'))
OPEN tableCursor 
FETCH NEXT FROM tableCursor INTO  @SQL
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @SQL
    EXEC (@SQL)
    FETCH NEXT FROM tableCursor INTO  @SQL
END
CLOSE tableCursor 
DEALLOCATE tableCursor 
PRINT '*** Finished ***'

错误

ALTER SCHEMA  [Storefront] TRANSFER [CadType].[proc_UpdateVertical];
Msg 15151, Level 16, State 1, Line 1
Cannot find the object 'proc_UpdateVertical', because it does not exist or you do not have permission.
ALTER SCHEMA  [Storefront] TRANSFER [CadType].[proc_UpdateElevationQty];
Msg 15151, Level 16, State 1, Line 1
Cannot find the object 'proc_UpdateElevationQty', because it does not exist or you do not have permission.
ALTER SCHEMA  [Storefront] TRANSFER [CadType].[proc_Update_Set_LeafIsActive];
Msg 15151, Level 16, State 1, Line 1

1 个答案:

答案 0 :(得分:1)

来自https://docs.microsoft.com/en-us/sql/t-sql/statements/alter-schema-transact-sql

  

ALTER SCHEMA schema_name TRANSFER [entity_type ::]   securable_name [;]

     

参数

     

schema_name 是当前数据库中架构的名称, 将移动安全性。不能是SYS或   INFORMATION_SCHEMA。

     

securable_name 是否将要包含的架构的一部分或两部分名称移动到架构中。

所以你需要

SELECT 'ALTER SCHEMA  ['+ @NewSchema +'] TRANSFER [' + @OldSchema + '].[' + DbObjects.Name + '];' AS Cmd