如何在EXEC中执行sp_OAMethod(@sql)

时间:2014-04-03 10:41:34

标签: sql sql-server

在我的存储过程中,我定义了以下部分:

SET @table = 'table_name'
SET @column = 'table_column'
WHILE (SELECT COUNT(1) FROM @table WHERE @column LIKE @filter) > 0
BEGIN
  SELECT TOP (1) @email = @column FROM @table WHERE @column LIKE @filter
  EXEC sp_OAMethod @object, 'Replace', @result OUT, @email, @employeeNewEmail
  UPDATE TOP (1) @table SET @column = @result WHERE @column LIKE @filter
END

这需要在许多表上完成,所以我想将WHILE语句包装到动态sql查询中

SET @query =
'WHILE (SELECT COUNT(1) FROM '+@table+' WHERE '+@column+' LIKE '+@filter+') > 0
BEGIN
  SELECT TOP (1) '+@email+' = '+@column+' FROM '+@table+' WHERE '+@column+' LIKE '+@filter+'
  EXEC sp_OAMethod '+@object+', ''Replace'', '+@result+' OUT, '+@email+', '+@employeeNewEmail+'
  UPDATE TOP (1) '+@table+' SET '+@column+' = '+@result+' WHERE '+@column+' LIKE '+@filter+'
END'

然后简单地

SET @table = 'table_name'
SET @column = 'table_column'
EXEC (@query)

不幸的是,这不起作用,我总是收到错误:

  

将varchar值','转换为数据类型int。

时转换失败

我错过了什么?

1 个答案:

答案 0 :(得分:0)

SET @table = 'table_name'
SET @column = 'table_column'

WHILE (SELECT COUNT(1) FROM '+@table+' WHERE '+@column+' LIKE '+@filter+') > 0
BEGIN
    SET @query ='SELECT TOP (1) '+@email+' = '+@column+' FROM '+@table+' WHERE '+@column+' LIKE '+@filter+'
    EXEC sp_OAMethod '+@object+', ''Replace'', '+@result+' OUT, '+@email+', '+@employeeNewEmail+'
    UPDATE TOP (1) '+@table+' SET '+@column+' = '+@result+' WHERE '+@column+' LIKE '+@filter+''
    exec(@query)
END