2017-02-11 153 views
0
create procedure dbo.move_pos 
(
@id int, 
@tbl varchar(50) 
)  
as  
begin  
declare @pos int  
exec('select '[email protected]+'=POS from '[email protected]+' where id='[email protected])  
exec('update '[email protected]+' set POS=POS+1 where POS<'[email protected])  
end 

在上述過程中,列POS的類型爲int。但是,當我米執行該過程它顯示以下錯誤:SQL存儲過程中的動態表名稱和參數

消息102,級別15,狀態1,行1

附近有語法錯誤 '='。

我使用SQL SERVER 2012.需要幫助。提前致謝 !!!

+0

選擇 '+ @ POS +'=從'+ @ TBL +的POS其中id ='+ @ ID西隧ü要做到與@ pos –

+0

試試這個 declare query varchar(100); (查詢) add @before查詢,id,pos –

+0

@YashveerSingh I m試圖移動一個項目頂部,所以我使用pos。 – SUPU

回答

0

我會推薦重新思考所有這些動態SQL存儲過程。
但是,如果你真的必須使用動態SQL,試試這個:

create procedure dbo.move_pos 
(
    @id int, 
    @tbl varchar(50) 
)  
as  
begin  
declare @sql nvarchar(max); 
set @sql = 'update ' + QUOTENAME(@tbl) + ' 
      set POS = POS + 1 
      where POS < (
       select POS 
       from ' + QUOTENAME(@tbl) + ' 
       where id = '+ cast(@id as nvarchar(10) 
      )' 

exec(@sql)  
end 
+0

謝謝@Zohar它工作正常。非常感謝你。 – SUPU