Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table-valued function, table variable and "Must declare scalar variable" error message

Tags:

sql-server

I am building a function that returns table result

ALTER FUNCTION [brm].[fnComputeScores_NEW]
(
    @var1 TINYINT
)
RETURNS 
@ret TABLE
(
    [producerid] INT
    ,[CityId] INT
    , CityName VARCHAR(100)
)
AS 
BEGIN


INSERT INTO @ret
        SELECT [producerid], [CityId] from producers

--placeholder

RETURN
END

everything is fine to this point

but code that I want to put in placeholder

UPDATE @ret
SET
    CityName = Cities.Name
FROM
    @ret JOIN Cities
        ON @ret.CityId= Cities.CityId

generates compilation error

Must declare the scalar variable "@ret".

Why? How to fix it?

like image 691
Cherven Avatar asked Sep 08 '26 08:09

Cherven


1 Answers

You can't reference the table variable outside of FROM. This is not exclusive to UPDATE... from http://msdn.microsoft.com/en-us/library/ms175010.aspx:

Outside a FROM clause, table variables must be referenced by using an alias...

...so you can try:

UPDATE r
SET
    r.CityName = c.Name
FROM
    @ret AS r 
    INNER JOIN dbo.Cities AS c
    ON r.CityId = c.CityId;
like image 79
Aaron Bertrand Avatar answered Sep 10 '26 17:09

Aaron Bertrand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!