sqlsql-serversql-server-2008

Update table variable


I have a table variable @searchResult:

DECLARE @searchResult TABLE (
    [name_template] NVARCHAR(50),
    [record_id] INT,
    [record_name] NVARCHAR(50)
);

And table [records]:

CREATE TABLE [records] (
    [record_id] INT IDENTITY(1, 1) PRIMARY KEY,
    [record_name] NVARCHAR(50)
)

@searchResult contains records with [name_template] filled only. I want to update it with latest [record_id] and [record_name] from [records] table that match [name_template].

I've tried folowing SQL query with no success:

UPDATE @searchResult
SET [record_id] = r.[record_id], [record_name] = r.[record_name]
FROM (
    SELECT TOP 1
          r.[record_id]
        , r.[record_name]
    FROM [records] AS r
    WHERE r.[record_name] LIKE [name_template]
    ORDER BY r.[record_id] DESC
) AS r;

Error message:

Invalid column name 'name_template'.

What is correct syntax to update @searchResult with desired values?


Solution

  • You need to do a CROSS APPLY on the tables.

    UPDATE @searchResult
    SET [record_id] = r.[record_id], 
        [record_name] = r.[record_name]
    FROM @searchResult SR
    CROSS APPLY (
        SELECT TOP 1 *
        FROM [records]
        WHERE [record_name] LIKE [name_template]   -- Your wish, but do you really need LIKE matching??
        ORDER BY [record_id] DESC
    ) AS r;