Sunday, February 12, 2012

Affecting SELECT rows to a table variable

Hi,

I would like to know how to add SELECT row to a table variable. It's not for my SELECT syntax(code following is just an ugly example) that I want help it's for the use of table variable.
Your help will greatly appreciate!!!

ex :
DECLARE @.MyTestVar table (
idTest int NOT NULL,
anotherColumn int NOT NULL)

SET @.MyTestVar = (SELECT idTest, anotherColumn FROM tTest)-- This cause an error :
-- Must declare the variable '@.MyTestVar'. ? What?

Use an Insert statement and treat the table variable as the table:

DECLARE @.MyTestVar table (
idTest int NOT NULL,
anotherColumn int NOT NULL)

Insert @.MyTestVar

SELECT idTest, anotherColumn FROM tTest

There is more information in the Books On-line:

Within its scope, a table variable may be used like a regular table. It may be applied anywhere a table or table expression is used in SELECT, INSERT, UPDATE, and DELETE statements. However, table may not be used in the following statements:

INSERT INTO table_variable EXEC stored_procedure

SELECT select_list INTO table_variable statements.

So, you cannot do a Select..Into or use the results of a stored procedure to populate the table variable.

|||

Thanks for the fast answer!

No comments:

Post a Comment