Hi @Debilon
If there are only id and string columns in your table, and the columns you want to update are FirstName, SecondName and ThirdName.
The first thing you need to do is add three columns to the original table.
ALTER TABLE your_Table_Name ADD LastName VARCHAR(30),
FirstName VARCHAR(30),
MiddleName VARCHAR(30);
Then use multiple CTE, put the outer select statement into a new CTE2, and UPDATE CTE2 SET FirstName = newFirstName...
;WITH CTE AS
(
SELECT *,ROW_NUMBER()OVER(PARTITION BY id ORDER BY CHARINDEX(Name1,name)) AS RNum
FROM OwnerNames
CROSS APPLY STRING_SPLIT(Name,' ')
),
CTE2 AS
(
SELECT id,Name,[1]AS New_LastName,
CASE WHEN [3] IS NULL THEN NULL ELSE [2] END AS New_FirstName,
CASE WHEN [3] IS NULL THEN [2] ELSE [3] END AS New_MiddleName
FROM CTE
PIVOT(MAX(value) FOR RNum IN([1],[2],[3]))P
where name is not null
)
UPDATE CTE2 SET FirstName = New_FirstName,
LastName = New_LastName,
MiddleName = New_MiddleName;
If the original table already has these three columns, then skip the ADD COLUMN step, just update CTE2.
For more details about Multiple CTE, please refer to this article: SQL Multiple CTE Syntax and T-SQL CTE Example
Also check this article for more examples: CTE With (INSERT/ DELETE/ UPDATE) Statement In SQL Server
Best regards,
LiHong