SQL Set Variable Within Insert Into Query – Programming, Pseudocode Example, C# Programming Example

SQL Set Variable Within Insert Into Query

SQL Declare Variable with Insert Statement

In this example you will learn How to make an INSERT INTO query with variables in SQL Server? We’ll go back to the first tutorial and modify it slightly to use variables in the INSERT INTO query instead of hard-coding the values.

How to write an INSERT INTO query using T-SQL variables?

1. Create the CLIENTS table with the NAME column declared as unique so that you do not insert the same client name twice. The NOCLIENT client number is auto-incremented to have a list followed by customer numbers.

2. In T-SQL code block, declare a variable for each column. Each of the data types declared in the variables corresponds to the data types of the columns. Insert the data with a simple INSERT INTO query that uses the two variables declared above.

Note that using variables in T-SQL is especially useful if you reuse the value of the variable multiple times.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.