What is the best way to achieve this
INSERT INTO @TableName (@ColumnNames)
EXEC sp_executesql @SQLResult;
Where @TableName
,
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]