2014-10-09 92 views
0

我想寫一個SQL過程砸桌子誰在他們的名字一定的模式。 喜歡的東西下面的代碼:條件子句DROP TABLE

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不與右表名替換。任何人都可以指引我朝着正確的方向發展。

+0

您當前的代碼將進入一個無限循環,由於這樣的事實,@ProcessedID永遠不會爲 – 2014-10-09 07:23:53

+0

是的,這更是一個僞代碼更好地解釋這個問題。 – surega 2014-10-09 11:36:09

回答

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