Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Filling a table variable with sp_executeSQL 1

Status
Not open for further replies.

Viruland

Programmer
Dec 6, 2000
61
0
0
BE
I want to fill a table variable with data from different tables.
I always get the following error code "Must declare the variable '@outputtable'.".
Can someone tell me what I'm doing wrong here?



declare @sourcetable sysname
declare @outputtable table (IDNr nchar(12), Description nvarchar(150))
declare counter int
declare @sql as nvarchar(2000)

set counter = 0

while counter < 3
BEGIN

IF COUNTER = 0
BEGIN

set @sourcetable = 'tbl_SalesComp'

END
ELSE IF COUNTER = 1
BEGIN

set @sourcetable = 'tbl_SalesExt'

END
ELSE IF COUNTER = 2
BEGIN

set @sourcetable = 'tbl_SalesSpec'

END


set @sql = 'INSERT INTO @tbl select IDNr, Description from ' + @sourcetable

exec sp_executesql @sql, N'@tbl table (IDNr nchar(12), Description nvarchar(150))', @outputtable

counter = counter + 1

END


Live fast, die young and leave a beautiful corpse behind.
 
You can't use table variable for this. You must use a Temp table. Dynamic SQL is executed in other JOB where you variables are not visible. Also you don't need such contruction here, you just could do:
Code:
declare @outputtable  table (IDNr nchar(12), Description  nvarchar(150))

INSERT INTO @outputtable (IDNr, Description)
SELECT IDNr, Description from tbl_SalesComp
UNION ALL
SELECT IDNr, Description from tbl_SalesExt
UNION ALL
SELECT IDNr, Description from tbl_SalesSpec

Borislav Borissov
VFP9 SP1, SQL Server 2000/2005.
MVP VFP
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top