Find and Drop SQL tables with a variable

  • backend: SQL Frontend: Access /vba

    Sql tables are created using variables.

    These tables need to be dropped after a user ends their session. They were not created as # or # temp tables because they are used throughout various functions.

    All tables have a table name that starts with 'u and a user name, such as 'uMDS-table1',

    'uMDS-table2'.

    Select name from sysobjects where xtype = 'u' and name like '%mds%'

    returns the tables. How would I loop through and delete each table? Or is there another way to do this?

    Any code example would be appreciated.

    Thanks

  • Be carefull but the way I do things like this where a specific condition can be met is like so.

    sp_MSForEachTable '

    if charindex(''mds'',''?'') != 0

    begin

    select ''?'' as verifyworksfirst

    --drop table ? --uncomment me once verified and want to run.

    end

    '

    This is just one possible way.

    "Don't roll your eyes at me. I will tape them in place." (Teacher on Boston Public)

  • Here is one more way:

    declare TablesToDelete cursor

    read_only

    for

    Select name from sysobjects where xtype = 'u' and name like '%mds%'

    declare @name varchar(40)

    declare @sql varchar(100)-- for drop command

    open TablesToDelete

    fetch next from TablesToDelete into @name

    while (@@fetch_status = 0)

    begin

    set @sql = 'drop table ' + @name

    exec (@sql)

    fetch next from TablesToDelete into @name

    end

    close TablesToDelete

    deallocate TablesToDelete

    go

    Test all possible ways for the best one.

    Diane

Viewing 3 posts - 1 through 2 (of 2 total)

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