Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Error 137: Must declare variable ...

Author  Topic 

metser
Starting Member

27 Posts

Posted - 2007-12-10 : 11:50:31
Hello,

I have the following SP, which gives out a "Error 137: Must declare variable @tmp_return_tbl" error.

This is the important part of the code:
.
.
.
-- DECLARE TABLE VARIABLE
DECLARE @tmp_return_tbl TABLE (tID int, Text_Title nvarchar(30), Text_Body nvarchar(100))

-- fill out table variable USING A SELECT FROM ANOTHER TABLE VARIABLE
-- NO PROBLEM HERE
INSERT INTO @tmp_return_tbl
SELECT TOP 1 * FROM @tmp_tbl
ORDER BY NEWID()

-- TRYING TO UPDATE A TABLE
UPDATE xTable
SET xTable.fieldY = xTable.fieldY + 1
WHERE xTable.tID = @tmp_return_tbl.tID --THIS PRODUCES THE ERROR
.
.
.

I know I cannot use a table variable in a JOIN without using an Alias, or use it directly in dynamic SQL (different scope) - but is this the problem here? What am I doing wrong?

Your help is much appreciated.

jhocutt
Constraint Violating Yak Guru

385 Posts

Posted - 2007-12-10 : 12:41:17
WHERE xTable.tID = @tmp_return_tbl.tID
should be
WHERE xTable.tID in(select tID from @tmp_return_tbl )


"God does not play dice" -- Albert Einstein
"Not only does God play dice, but he sometimes throws them where they cannot be seen."
-- Stephen Hawking
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2007-12-10 : 12:47:15
quote:
Originally posted by jhocutt

WHERE xTable.tID = @tmp_return_tbl.tID
should be
WHERE xTable.tID in(select tID from @tmp_return_tbl )



Joins are preferred over subqueries.

UPDATE x
SET fieldY = x.fieldY + 1
FROM xTable x
INNER JOIN @tmp_return_tbl t
ON x.tID = t.tID

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/
Go to Top of Page

metser
Starting Member

27 Posts

Posted - 2007-12-10 : 14:58:04
Thank you both for your answers!
Go to Top of Page
   

- Advertisement -