declare @comp char(4)
set @comp='8000'
select * from OPENROWSET('SQLOLEDB', 'server=AAANTS01;uid=test1;pwd=test1',
'select comp_code,dept_code,badge,c_name from test1 where comp_code='+@comp+' and status=''3''')

解决方案 »

  1.   

    declare @comp char(4)
    set @comp='8000'
    declare @sql varchar(2000)
    set @sql='select * from OPENROWSET(''SQLOLEDB'', ''server=AAANTS01;uid=test1;pwd=test1'',
    ''select comp_code,dept_code,badge,c_name from test1 where comp_code='''+@comp+''' and status=''3'')'
    exec(@sql)
      

  2.   

    变量的作用域在定义的的过程中. openrowset是内是一个新的处理过程, 外部定义的变量自然不起作用.sql 没有全局变量, 因此楼主的这个处理无法直接用变量处理.
    由于openrowset只支持常量, 不支持表达式和变量. 因此2楼的方法才是对的.