我有多个表名,如g_str_a,g_str_ab,g_str_abc。我想删除所有那些以SQL Server 2008上的g_str开头的表。
DROP Tables like 'g_str'
会有帮助吗?
请帮我解决这个问题。
答案 0 :(得分:4)
SELECT
'DROP TABLE ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(name) + ';'
FROM sys.tables
WHERE name LIKE 'g\_str%' ESCAPE '\'
然后查看脚本并运行它。
如果您需要完全自动化的解决方案,您还可以concatenate the result成一个字符串并使用EXEC
执行。
答案 1 :(得分: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;
答案 2 :(得分: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