select @id=max(cast(substring(@fields,11,4) as int)) 
from   @tables  where  (@fields) like @Str2
改为:
declare @ss nvarchar(1000)set @ss='select @id = max(cast(substring('+@fields+',11,4) as int)) from '+  @tables+' where '+@fields+' like '''+@Str2+''''exec sp_executesql  @ss ,N'@id int output',@id output

解决方案 »

  1.   

    declare @ls_str varchar(300)
    select @ls_str = 
    'select @id=max(cast(substring(@fields,11,4) as int)) 
    from  ' + @tables + ' where  (' + @fields + ') like' + @Str2
    exec(@ls_str,N'@id int output',@id output)
      

  2.   

    to fanmb(随便聊聊) 
    exec(@ls_str,N'@id int output',@id output)
    这句话出错!不过还是要谢谢!to tj_dns(愉快的登山者) 
    我一定已你为楷模,谢谢了,可以了!马上结账!
      

  3.   

    to tj_dns(愉快的登山者) 
    能解释一下' like '''+@Str2+'''',为什么要这么多引号?
    还有一个就是exec sp_executesql  @ss ,N'@id int output',@id output
    的具体含义是什么?为什么@id要写两次?谢谢了,我这没有帮助文件!
      

  4.   

    哈哈,我有帮助,我知道!
    sp_executesql [@stmt =] stmt
    [
        {, [@params =] N'@parameter_name  data_type [,...n]' }
        {, [@param1 =] 'value1' [,...n] }
    ]参数
    [@stmt =] stmt包含 Transact-SQL 语句或批处理的 Unicode 字符串,stmt 必须是可以隐式转换为 ntext 的 Unicode 常量或变量。不允许使用更复杂的 Unicode 表达式(例如使用 + 运算符串联两个字符串)。不允许使用字符常量。如果指定常量,则必须使用 N 作为前缀。例如,Unicode 常量 N'sp_who' 是有效的,但是字符常量 'sp_who' 则无效。字符串的大小仅受可用数据库服务器内存限制。stmt 可以包含与变量名形式相同的参数,例如:N'SELECT * FROM Employees WHERE EmployeeID = @IDParameter'stmt 中包含的每个参数在 @params 参数定义列表和参数值列表中均必须有对应项。[@params =] N'@parameter_name  data_type [,...n]'字符串,其中包含已嵌入到 stmt 中的所有参数的定义。该字符串必须是可以隐式转换为 ntext 的 Unicode 常量或变量。每个参数定义均由参数名和数据类型组成。n 是表明附加参数定义的占位符。stmt 中指定的每个参数都必须在 @params 中定义。如果 stmt 中的 Transact-SQL 语句或批处理不包含参数,则不需要 @params。该参数的默认值为 NULL。[@param1 =] 'value1'参数字符串中定义的第一个参数的值。该值可以是常量或变量。必须为 stmt 中包含的每个参数提供参数值。如果 stmt 中包含的 Transact-SQL 语句或批处理没有参数,则不需要值。n附加参数的值的占位符。这些值只能是常量或变量,而不能是更复杂的表达式,例如函数或使用运算符生成的表达式。返回代码值
    0(成功)或 1(失败)结果集
    从生成 SQL 字符串的所有 SQL 语句返回结果集。