简体   繁体   中英

How to Write alter statement to alter Temp Table with Dynamic name

I have written the following query - what is my fault? Please guide me

set @sqlAlter = 'alter table #RD_Temp' + @UserNum + ' add ' + @columnname + ' DECIMAL(18,2)'    
Execute sp_executesql @sqlAlter

Here #RD_Temp'+ @UserNum is the dynamic name for my temp table and @UserNum = 1 which is changed as per user and @columnname is dynamic column.

I get this error:

Cannot find the object "#RD_Temp1" because it does not exist or you do not have permissions.

Instead of directly using #RD_Temp , you should use tempdb..#RD_Temp .

eg

set @sqlAlter = 'alter table tempdb..#RD_Temp' + @UserNum + ' add ' + @columnname + ' DECIMAL(18,2)' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM