0

我有多个表名,例如 g_str_a 、 g_str_ab 、 g_str_abc 。我想删除 SQL Server 2008 上所有以 g_str 开头的表。

DROP Tables like 'g_str'帮助吗?

请帮我写剧本。

4

3 回答 3

4
SELECT 
'DROP TABLE ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(name) + ';'
FROM sys.tables
WHERE name LIKE 'g\_str%'  ESCAPE '\'

然后查看脚本并运行它。

如果您需要完全自动化的解决方案,您还可以将结果连接成单个字符串并执行。EXEC

于 2012-10-29T16:29:34.267 回答
3

您可以使用动态 SQL:

DECLARE @SQL NVARCHAR(MAX) = '';

SELECT  @SQL = @SQL + 'DROP TABLE ' + QUOTENAME(SCHEMA_NAME([Schema_ID])) + '.' + QUOTENAME([name]) + ';'
FROM    sys.tables
WHERE   Name LIKE 'g\_str%' ESCAPE('\');

EXECUTE SP_EXECUTESQL @SQL;
于 2012-10-29T16:30:17.477 回答
1

以下查询将自动删除表:

    BEGIN TRANSACTION

    DECLARE @tmpTablesToDelete TABLE ( 
                                        RowNumber INT PRIMARY KEY
                                       ,Query NVARCHAR(MAX)
                                     )

    INSERT INTO
            @tmpTablesToDelete 
    SELECT 
         RowNumber = ROW_NUMBER() OVER (ORDER BY (SELECT (0)))
        ,'DROP TABLE '+schemas.name+'.'+objects.name AS Query
    FROM 
        sys.objects 
    INNER JOIN
        sys.schemas
    ON
        schemas.schema_id = objects.schema_id
    WHERE 
        type = 'U' AND objects.name like 'g_str%'

    DECLARE @Counter INT
    SELECT @Counter = MAX(RowNumber) FROM @tmpTablesToDelete

    WHILE(@Counter > 0) BEGIN

        DECLARE @Query NVARCHAR(MAX)

        SELECT @Query = Query FROM @tmpTablesToDelete WHERE RowNumber = @Counter

        PRINT @Query

        EXEC sp_executesql @statement = @Query

        SET @Counter = @Counter - 1

    END

    COMMIT TRANSACTION
于 2012-10-29T16:33:02.780 回答