Published on: 06 Dec, 2020

How to declare table variable in TSQL?

Tumblr Digg Google Plus

In this tutorial, we are going to learn how to declare a table in TSQL. We are going to insert some records into this table and perform some query selection against it.

Let's start with creating a product table that will have the following column fields.

  • Id
    This column will be an integer type.
     
  • Name
    This column will be a nvarchar type.
     
  • Price
    This column will be a money type.

When declaring a variable in TSQL. It will always start with the symbol @. Here is the sample full TSQL Query code to create the table. Then inserting the sample records and perform a query selection against our sample table.


DECLARE @ProductTable Table(
	Id INT,
	ProductName nvarchar(100),
	Price MONEY
);

INSERT INTO @ProductTable (Id, ProductName, Price) VALUES (1, 'Computer', 1229.95);
INSERT INTO @ProductTable (Id, ProductName, Price) VALUES (1, 'Monitor', 280.59);
INSERT INTO @ProductTable (Id, ProductName, Price) VALUES (1, 'Printer', 160.00);

SELECT * 
FROM @ProductTable
ORDER BY Price

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.