How can i rename a table using SQL

  • given i have got a table named f_policy

    i wanted to rename that table into

    @month_f_policy where @month is the current month. so this month would be 05_f_policy and december would be 12_f_policy

    how can i able to do that in SQL?

  • Hi,

    a quick and dirty solution could be

    declare @new_name varchar(50)

    set @new_name = cast(datepart(mm,getdate())as varchar(30)) + '_f_policy'

    exec sp_rename 'f_policy', @new_name

    Note: This returns a 5_f_policy instead of 05_f_policy. It needs to be fixed

    Cheers,

    Frank

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

  • Check the dependencies with sp_depends before renaing the object.

  • Oops,

    quote:


    Check the dependencies with sp_depends before renaing the object.


    definetely DO this, when you received the message in QA it is too late!

    Cheers,

    Frank

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

  • Hi ngkh,

    here is a fix for months <10

    set @new_name = datepart(mm,getdate())

    if (@new_name < 10)

    begin

    set @new_name = '0'+ cast(@new_name as varchar(50)) +'_'

    end

    else

    begin

    set @new_name = cast(@new_name as varchar(50)) + '_'

    end

    Not sure if you really need the begin...end statements. Seems to work without, too.

    Cheers,

    Frank

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

Viewing 5 posts - 1 through 4 (of 4 total)

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