簡體   English   中英

SQL存儲過程中的動態表名稱和參數

[英]Dynamic Table Name and Paramers in SQL Stored Procedure

create procedure dbo.move_pos
(
@id int,
@tbl varchar(50)
)    
as    
begin    
declare @pos int    
exec('select '+@pos+'=POS from '+@tbl+' where id='+@id)    
exec('update '+@tbl+'  set POS=POS+1 where POS<'+@pos)    
end

在上述過程中,POS列的類型為int。 但是,當我執行此過程時,它顯示以下錯誤:

Msg 102,第15級,狀態1,第1行

'='附近的語法不正確。

我正在使用SQL SERVER2012。需要幫助。 提前致謝 !!!

我建議重新考慮所有這些動態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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM