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?
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;
Try this:
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];
Update:
Seems to be working fine from what I've tested:
Create table and table variable:
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)
);
Populate with sample data:
INSERT INTO [records] ([record_name]) VALUES('a'), ('a'), ('a'), ('b'), ('b')
INSERT INTO @searchResult ([name_template]) VALUES ('a'), ('b')
Update table variable:
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];
Check results:
SELECT *
FROM records
SELECT *
FROM @searchResult
DROP TABLE records
Results:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With