Share via

Need script help!

Potter123 260 Reputation points
2023-08-07T08:13:17.5433333+00:00

Hello.

I need script help. I know the insert statement.

Insert into table(col) values();

But I now need to use dynamic SQL for insertion.

I know nothing about dynamic sql, can someone share the idea?

Thanks in advance!

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

Anonymous
2023-08-07T08:20:02.1733333+00:00

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:

User's image

If you need to write into stored procedures, you can refer to this official document, which contains an example of dynamic insertion.

https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-ver16

Best regards,

Percy Tang

Was this answer helpful?

1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 134.7K Reputation points MVP Volunteer Moderator
    2023-08-07T21:13:16.9866667+00:00

    If you want to learn about dynamic SQL, there is an article on my web site: The Curse and Blessings of Dynamic SQL

    Yes, it's long, but dynamic SQL is an advanced feature that easily lends itself to abuse.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.