I try to update a column in a temporary table by concatenating rows from another table.
Look at this:
DECLARE @Test VARCHAR(MAX);
CREATE TABLE #Test
(
EmployeeId INT
,Html VARCHAR(MAX)
);
CREATE TABLE #EmployeeItems
(
EmployeeId INT
,ItemNo INT
);
INSERT INTO #EmployeeItems (EmployeeId, ItemNo)
VALUES
(1, 1)
,(1, 2);
INSERT INTO #Test (EmployeeId, Html) VALUES (1, '<div class="first">');
SET @Test = '<div class="first">';
UPDATE T SET Html += '<div class="second">' + CAST(E.ItemNo AS VARCHAR) + '</div>'
FROM #Test AS T
JOIN #EmployeeItems AS E ON T.EmployeeId = E.EmployeeId;
SELECT @Test += '<div class="second">' + CAST(E.ItemNo AS VARCHAR) + '</div>'
FROM #Test AS T
JOIN #EmployeeItems AS E ON T.EmployeeId = E.EmployeeId;
UPDATE #Test SET Html += '</div>';
SET @Test += '</div>';
SELECT Html FROM #Test;
SELECT @Test;
DROP TABLE #Test;
DROP TABLE #EmployeeItems;
The column in the #Test table contains: <div class="first"><div class="second">1</div></div>
And the @Test variable contains: <div class="first"><div class="second">1</div><div class="second">2</div></div>
Why is this? What difference is it? I thought I would get the same results but in the table case it only concatenates one row, the first.
What should I do instead to update my table without running a cursor?
EDIT
My original problem comes from something like this:
My input data is
CREATE TABLE #Actions(EmployeeId INT,EmployeeName VARCHAR(100),ActionStart TIME,ActionEnd TIME,Type VARCHAR(10));
INSERT INTO #Actions(EmployeeId,EmployeeName,ActionStart,ActionEnd, Type)
VALUES (1,'Bob','09:00','12:00', 'action'),(1,'Bob','14:30','16:00', 'action'),(1,'Bob','18:00','20:00', 'event'),(2,'Susan','10:00','12:00', 'action');
I want output like this
<div class="employee" employeeid="1" employeename="Bob">
<div class="action" start="09:00" end="12:00" type="action"></div>
<div class="action" start="14:30" end="16:00" type="action"></div>
<div class="action" start="18:00" end="20:00" type="event"></div>
</div>
<div class="employee" employeeid="2" employeename="Susan">
<div class="action" start="10:00" end="12:00" type="action"></div>
</div>
Like the first example this is a simplified example. But if I solve a case I can solve my problem. How would you do this with the FOR XML clause?
Think of the variable concatenation as a quirk; it’s unsupported behavior that gets used a lot in code 🙂 If you want to keep using it, you could modify your UPDATE statement like so:
An alternate method would be to use the FOR XML syntax to concatenate
Or (and perhaps best), just build your XML document directly.
Additional Answer for edited question: