Got a complex SELECT query, from which I would like to insert all rows into a table variable, but T-SQL doesn't allow it.
Along the same lines, you cannot use a table variable with SELECT INTO or INSERT EXEC queries. http://odetocode.com/Articles/365.aspx
Short example:
declare @userData TABLE(
name varchar(30) NOT NULL,
oldlocation varchar(30) NOT NULL
)
SELECT name, location
INTO @userData
FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30
The data in the table variable would be later used to insert/update it back into different tables (mostly copy of the same data with minor updates). The goal of this would be to simply make the script a bit more readable and more easily customisable than doing the SELECT INTO
directly into the right tables.
Performance is not an issue, as the rowcount
is fairly small and it's only manually run when needed.
...or just tell me if I'm doing it all wrong.
OK, Now with enough effort i am able to insert into @table using the below :
The main thing here is selecting columns to insert .
You could try using temporary tables...
You skip the effort to declare the table that way... Helps for adhoc queries...This creates a local temp table which wont be visible to other connections unless you use the same connection across your app.
if you require variables it can be declared this way :
First create a temp table :
Step 1:
**Step 2: ** Insert Some value in Temp table .
Step 3: Declare a table Variable to hold temp table data.
Step 4: select value from temp table and insert into table variable.
Finally value is inserted from a temp table to Table variable
Step 5: Can Check inserted value in table variable.
You can also use common table expressions to store temporary datasets. They are more elegant and adhoc friendly:
The purpose of
SELECT INTO
is (per the docs, my emphasis)But you already have a target table! So what you want is
And in this syntax, it's allowed for
MyTable
to be a table variable.Try something like this: