调用EXEC()会生成错误:找不到存储过程

时间:2011-12-05 08:40:54

标签: sql-server tsql

我需要在表上调用一个名称只会在运行时知道的删除。

我有一个存储过程,它动态地使用tablename和criteria来表示delete语句,然后将该字符串作为参数传递给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

...

这是错误:

  

无法找到存储过程'DELETE FROM myTable WHERE id = 1111'

4 个答案:

答案 0 :(得分:20)

没有括号的

EXEC尝试调用过程。

尝试EXEC(@dynDelete)

答案 1 :(得分:3)

你需要写上     EXEC(@dynDelete)

答案 2 :(得分: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)

答案 3 :(得分:1)

如果使用EXEC

,则从SqlDataSource删除DeleteCommandType