重命名多个表

时间:2018-02-20 21:22:32

标签: sql sql-server sql-server-2012

如何使用相同的postfix重命名多个表,例如dbo.Denali_YLM_RedemptionStaging到dbo.Denali_YLM_RedemptionStaging_round3。 我想在12个表的末尾添加round3。请建议

2 个答案:

答案 0 :(得分:0)

您可以使用sp_msforeachtable。有关详细信息,请参阅此处:https://blogs.msdn.microsoft.com/mosharaf/2013/10/23/select-everything-from-every-table-in-every-database/

答案 1 :(得分:0)

如果要一次重命名表,则应使用动态SQL。对于12只复制和粘贴会更快。此查询将_round3添加到以RedemptionStaging

结尾的所有表中
declare @cmdNum int
declare @i int = 1
declare @cmd varchar(1000)

declare @t table(
    cmd varchar(1000)
    , rn int
)

insert into @t
select
    'exec sp_rename ''' + table_name + ''', ''' + table_name + '_round3'''
    , row_number() over (order by (select 1))
from
    information_schema.tables
where
    table_schema = 'dbo'
    and table_name like '%RedemptionStaging'


select @cmdNum = count(*) from @t

while @i <= @cmdNum
begin
    select @cmd = cmd from @t where rn = @i
    exec (@cmd)
    set @i = @i + 1
end