更新表变量

时间:2016-03-28 13:27:29

标签: sql sql-server sql-server-2008

我有一个表变量@searchResult

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

[records]

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

@searchResult包含仅填充[name_template]的记录。我想使用与[record_id]匹配的[record_name]表中的最新[records][name_template]进行更新。

我尝试过SQL查询但没有成功:

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;

错误讯息:

  

列名称无效' name_template'。

使用所需值更新@searchResult的正确语法是什么?

2 个答案:

答案 0 :(得分:4)

您需要在表格上执行CROSS APPLY

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;

答案 1 :(得分:2)

试试这个:

UPDATE t
SET [record_id] = r.[record_id], 
    [record_name] = r.[record_name]
FROM @searchResult t
INNER JOIN 
(
    SELECT MAX([record_id]) As [record_id]
            ,[record_name]
    FROM [records]
    GROUP BY [record_name] 
) r
ON r.[record_name] LIKE t.[name_template];

<强>更新
似乎从我测试过的工作中做得很好:

创建表和表变量:

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

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

填充样本数据:

INSERT INTO [records] ([record_name]) VALUES('a'), ('a'), ('a'), ('b'), ('b')

INSERT INTO @searchResult ([name_template]) VALUES ('a'), ('b')

更新表格变量:

UPDATE t
SET [record_id] = r.[record_id], 
    [record_name] = r.[record_name]
FROM @searchResult t
INNER JOIN 
(
    SELECT MAX([record_id]) As [record_id]
            ,[record_name]
    FROM [records]
    GROUP BY [record_name] 
) r
ON r.[record_name] LIKE t.[name_template];

检查结果:

SELECT *
FROM records

SELECT *
FROM @searchResult

DROP TABLE records 

结果:

records
record_id   record_name
----------- -----------
1           a
2           a
3           a
4           b
5           b

@searchResult
name_template   record_id   record_name
-------------   ---------   -----------
a               3           a
b               5           b