2011-12-05 50 views
11

我需要調用一個表名稱的刪除只會在運行時知道。我有一個存儲過程動態地用表名和條件制定刪除語句,然後將該字符串作爲參數傳遞給EXEC()函數(顯然,這在所有事務中都是這樣的)。調用EXEC()生成錯誤:找不到存儲過程

當我運行存儲過程時,我得到一個錯誤 - 無法找到存儲過程 - 引用我動態制定併發送給EXEC()的語句。

這裏是我的代碼:

DECLARE @dynTab AS varchar(50), @dynDelete AS varchar(255) 
    DECLARE @crsr CURSOR 
    SET @crsr = CURSOR FAST_FORWARD 
    FOR 
    SELECT dyn_tablename FROM dyn_tab WHERE dyn_doc_type_id IN (SELECT doc_id FROM tree_tab WHERE id = @id) AND dyn_tablecreated = 1 

OPEN @crsr 
FETCH NEXT FROM @crsr 
INTO @dynTab 

WHILE @@FETCH_STATUS = 0 AND @@ERROR = 0 
    BEGIN 
     SET @dynDelete = 'DELETE FROM ' + @dynTab + ' WHERE id = ' + @id 
     EXEC @dynDelete 

     FETCH NEXT FROM @crsr 
     INTO @dynTab 
    END 

      CLOSE @crsr 
     DEALLOCATE @crsr 
     IF @@ERROR <> 0 
     BEGIN 
      ROLLBACK TRAN 
      return 0 
     END 

...

這裏的錯誤:

Could not find stored procedure 'DELETE FROM myTable WHERE id = 1111'

回答

18

EXEC沒有括號試圖調用的過程。

嘗試EXEC(@dynDelete)

3

你需要寫
EXEC(@dynDelete)

1

使用EXEC()EXECUTE()爲執行以下SQL查詢:

SET @dynDelete = 'DELETE FROM ' + @dynTab + ' WHERE id = ' + @id 
EXEC(@dynDelete) 

OR

SET @dynDelete = 'DELETE FROM ' + @dynTab + ' WHERE id = ' + @id 
EXECUTE(@dynDelete) 
1

如果使用從SqlDataSource中刪除DeleteCommandType EXEC