SQL Server : insert stored procedure with dynamic table name

前端 未结 1 889
生来不讨喜
生来不讨喜 2020-12-21 21:13

I am trying to create a stored procedure for inserting new data. Basically I am getting an error about \'declare the table variable@tablename\'.

I tried:

         


        
相关标签:
1条回答
  • 2020-12-21 22:03

    Prepare dynamic insert statement as below:

    CREATE procedure [dbo].[spInsertProc](@table_name varchar(max))
    as
    begin
      declare @name varchar(50)='Sandip';
      declare @description varchar(50)='SE'; 
    
      Declare @Query VARCHAR(MAX)
      SET @Query='Insert Into '+@table_name+' ([name], [description])
        Values (
           '''+@name+''',
            '''+@description+''')'
      EXEC(@Query);
      PRINT(@Query); 
    end
    
    0 讨论(0)
提交回复
热议问题