Inserting Data When the Column Name Is a Variable

I want to use the T-SQL INSERT statement to insert data into a table. However, the column name is a variable, and the INSERT command doesn't accept a variable argument for a column name. How can I accomplish the insert?

You can insert the data by using the sp_executesql stored procedure or the T-SQL EXEC statement, which Listing 1 shows. This sample code demonstrates how SQL Server uses the T-SQL EXEC statement to build and execute a dynamic string.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish