DROP表的条件子句

时间:2014-10-09 06:48:15

标签: sql

我试图写一个sql过程来删除名字中有某种模式的表。 类似下面的代码:

DECLARE @temp TABLE 
(
  ID bigint IDENTITY(1,1),
  tabname sysname NOT NULL
)
INSERT INTO @temp
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%:%'

DECLARE @ProcessedID bigint = 0
DECLARE @tablename sysname
SELECT @ProcessedID = ID, @tablename = tabname FROM @temp WHERE ID > @ProcessedID ORDER BY ID DESC
WHILE(@ProcessedID IS NOT NULL)
BEGIN
    DROP TABLE dbo.[@tablename]
    SELECT @ProcessedID = ID, @tablename = tabname FROM @temp WHERE ID > @ProcessedID ORDER BY ID DESC
END

但@tablename不会替换为正确的表名。任何人都可以指出我正确的方向。

1 个答案:

答案 0 :(得分:1)

当您想要使用变量名作为参数时,需要动态执行此操作,因此需要将其包装在字符串中并执行该字符串,然后对WHILE条件进行一些小的更改以适应。

我正确地做了这样的事情:

DECLARE @temp TABLE 
(
  ID bigint IDENTITY(1,1),
  tabname sysname NOT NULL
):
INSERT INTO @temp
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%:%';

DECLARE @tablename VARCHAR(255);
DECLARE @Count INT = ISNULL((SELECT COUNT(*) FROM @temp AS t), 0);

WHILE(@Count > 0)
BEGIN

    SELECT @tablename = tabname FROM @temp AS t; --if the order of drop is not significant

    EXEC('DROP TABLE dbo.[' + @tablename+ ']'); 
    DELETE FROM @temp WHERE tabname = @tablename;
    SET @Count =  ISNULL((SELECT COUNT(*) FROM @temp AS t), 0);
END