Additional SQL Server features and topics not covered by specific categories
Hi @15431565
You can try this script.
DECLARE @SQL nvarchar(400)
DECLARE @TableName nvarchar(max)
DECLARE @ColName nvarchar(max)
DECLARE @Insertvalue nvarchar(max)
set @TableName = 'test'
set @ColName = 'colB'
set @Insertvalue = 'just a test'
set @SQL = N'INSERT INTO ' + @TableName + '(' + @ColName + ')' + ' VALUES (' + QUOTENAME(@Insertvalue,'''') + ');'
print @SQL;
Exec sp_executesql @SQL,N'@TableName nvarchar(max),@ColName nvarchar(max),@Insertvalue nvarchar(max)',@TableName,@ColName,@Insertvalue;
select * from test;
Output:
If you need to write into stored procedures, you can refer to this official document, which contains an example of dynamic insertion.
Best regards,
Percy Tang