Dynamic T-SQL stored procedure to insert in differents tables

后端 未结 3 663
终归单人心
终归单人心 2021-01-27 16:20

What is the best way to achieve this

INSERT INTO @TableName (@ColumnNames)
    EXEC sp_executesql @SQLResult;

Where @TableName,

3条回答
  •  被撕碎了的回忆
    2021-01-27 16:47

    Use EXECUTE sp_executesql @sql, here is example:

    create proc sp_DynamicExcuteStore 
    @TableName varchar(50),
    @ColumnNames varchar(50),
    @SQLResult varchar(max)
    as
    declare @sql nvarchar(max) = '
    INSERT INTO '+@TableName+' ('+@ColumnNames+')
        EXEC sp_executesql '+@SQLResult
    EXECUTE sp_executesql @sql
    go
    create proc sp_test
    as
    select 'test' + convert(varchar,RAND())
    go
    CREATE TABLE [dbo].[Test](
        [text1] [nvarchar](500) NULL
    ) ON [PRIMARY]
    
    GO
    DECLARE @return_value int
    
    EXEC    @return_value = [dbo].[sp_DynamicExcuteStore]
            @TableName = N'Test',
            @ColumnNames = N'text1',
            @SQLResult = N'proc_test'
    
    SELECT  'Return Value' = @return_value
    
    GO
    
    SELECT TOP 1000 [text1]
      FROM [test].[dbo].[Test]
    

提交回复
热议问题