9

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. :)

Brent Arias
  • 29,277
  • 40
  • 133
  • 234

1 Answers1

16

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;
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
  • Exactly what I was going to say. The syntax for declaring table variables don't allow for something so dynamic. – Yuck Jun 30 '11 at 18:51