Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a Table Variable Based on Select Statement

I want to declare a table variable and fill it with a select, without having to explicitly define its columns. Does T-SQL allow something like this:

DECLARE @people TABLE() SELECT * FROM Persons;

Hypothetically, the above statement would match column types identically, and fill the @people table variable at the same time. :)

like image 845
Brent Arias Avatar asked Jun 30 '11 18:06

Brent Arias


People also ask

Can you DECLARE a variable in a SELECT statement?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.

How do you set a variable in a SELECT statement in SQL Server?

Setting a Value in a Transact-SQL Variable To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

How do you use variables in a SELECT statement?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.


1 Answers

You can't do it with a table variable since a variable has to be declared before it can be used, but you could use a temp table instead.

SELECT * INTO #people FROM Persons;
like image 181
Joe Stefanelli Avatar answered Nov 15 '22 22:11

Joe Stefanelli