T-SQL Rename Multiple Tables

  • I am looking to rename a lot of tables using a wildcard,

    for example, the table names are:

    OrderItem

    OrderItems

    OrderItemss

    I would like them to be renamed to:

    OrderItem2

    OrderItems2

    OrderItemss2

    Can this be done using a wildcard so I don't have to specify the full table name? Thanks.

  • Something like this?

    -- Set up test data

    declare @tablelist table (

    table_name sysname primary key,

    new_table_name sysname null

    );

    insert into @tablelist (table_name)

    select 'OrderItem' union all select 'OrderItems' union all select 'OrderItemss'

    -- Enumerate new table name

    update @tablelist set new_table_name = table_name + '2'

    -- Print out rename scripts to run

    select 'EXEC dbo.sp_rename @objname = N''' + table_name + ''', @newname = N''' + new_table_name + ''', @objtype = N''OBJECT'''

    from @tablelist

  • thanks for the code. Not exactly what I was looking to do

    I want to able to specify a wildcard like

    'O%' to '02%' can I do something like this?

  • Can you give a concrete example or two on how the wildcard should work?

  • Rename Table '0%' to '02%'

    So that all the tables in the database would have a number 2 in the name.

  • The SET clause in the UPDATE statement will need to be manually constructed, I'm afraid. e.g.

    update @tablelist set new_table_name = '02' + right(table_name, len(table_name) - 2)

    where table_name like '0%'

    Also consider a CLR based function that will let you specify regular expressions if you find yourself doing advanced string search and replace.

  • I am not familiar with using CTE. I usually work with an older version of SQL Server. I ran the SET script, it is showing the error:

    Msg 1087, Level 15, State 2, Line 1

    Must declare the table variable "@tablelist".

  • CLR = Common Language Runtime, i.e. .Net code

    CTE = Common Table Expressions

    The previous UPDATE statement was not the entire solution, but just an example on how to modify my original script to implement the specific wildcard-equivalent.

    The @tablelist is a table variable (I think this feature was introduced in SQL 2005). Unlike a temporary table (the ones with a # or ##), a table variable has the same scope of any other local variable (within the function, stored procedure, or batch that it is declared in).

  • I figured out where I was having a problems when I was doing a lookup with sys.tables it was only bring back the second part of the name. So when i executed a sp_rename it would throw an error. the full name is Customer.OrderItems. Thanks for the help

Viewing 9 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic. Login to reply