日期:2014-05-18  浏览次数:20417 次

使用execute()出錯
當我在SQL   SERVER2000   的查詢分析器上這樣用execute時會出現錯誤:

declare   @_tmp   varchar(8000),@_id_code   varchar(230)
select   @_id_code= 'aaa '

SELECT   @_tmp= 'insert   into   sod_tmp(sod_id,sol_id,soh_id)   '
+ '   SELECT   thisid,line_id,header_id   from   sod_planned_unreleased_v   '
+ '   WHERE   sol_orgid=1   and   soh_orgid=1   AND   soh_entry_status_code   not   in   (select   code_string   from   sod_tmp2   where   id_code=@_id_code) '
execute(@_tmp)

錯誤如下:

Server:   Msg   137,   Level   15,   State   2,   Line   1
Must   declare   the   variable   '@_id_code '.

我@_id_code明明已經declare   了,為啥還會出現這個錯誤,各位兄弟,請指導一下,怎樣做才對



------解决方案--------------------
declare @_tmp nvarchar(4000),@_id_code varchar(230)
select @_id_code= 'aaa '

SELECT @_tmp= 'insert into sod_tmp(sod_id,sol_id,soh_id) '
+ ' SELECT thisid,line_id,header_id from sod_planned_unreleased_v '
+ ' WHERE sol_orgid=1 and soh_orgid=1 AND soh_entry_status_code not in (select code_string from sod_tmp2 where id_code=@_id_code) '

execute sp_executesql @_tmp,N '@_id_code varchar(230) input ',@_id_code input
------解决方案--------------------
declare @_tmp varchar(8000),@_id_code varchar(230)
select @_id_code= 'aaa '

SELECT @_tmp= 'insert into sod_tmp(sod_id,sol_id,soh_id) '
+ ' SELECT thisid,line_id,header_id from sod_planned_unreleased_v '
+ ' WHERE sol_orgid=1 and soh_orgid=1 AND soh_entry_status_code not in (select code_string from sod_tmp2 where id_code= ' ' '+@_id_code+ ' ' ') '
exec(@_tmp)

------解决方案--------------------

declare @_tmp varchar(8000),@_id_code varchar(230)
select @_id_code= 'aaa '
這兩句一起放入@_tmp中吧