Inserting Data When the Column Name Is a Variable

Microsoft’s SQL Server development team provides code that shows how to get around the T-SQL INSERT command’s lack of support for a variable argument.

ITPro Today logo in a gray background | ITPro Today

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.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like