IMG-LOGO

How to declare table variable in TSQL?

andy - 06 Dec, 2020 927 Views 0 Comment

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.

Related Articles

How to restore database using SQL query in TSQL?

If you have a database backup bak file extension and want to restore it using SQL query You can use the built in RESTORE DATABASE function Remember in order to be able to restore a database successfully You need to ...

How to get all table sizes in TSQL?

To get the information about how much space or size used by tables You can retrieve the size information by linking multiple tables in sys tables There are two tables that hold this information The first one is the sys ...