Forum Discussion
mrung01
Jan 26, 2024Copper Contributor
SQL replace part of a string
I am trying to replace part of a string in the tagpath column shown below. I need to replace edge nodes with cloud anywhere that the rest of the string path is equal. There are thousands of records l...
mrung01
Jan 27, 2024Copper Contributor
Thank you, sorry I didn't specify. Yes I need to update the existing table. I was hoping there would be an "easy" way to do it. Appreciate the reply.
LainRobertson
Jan 28, 2024Silver Contributor
Hi, Matt.
Here's an UPDATE variation using the same data structures and data from above.
This UPDATE will take this original data:
And produce this (where only row 1 has updated):
Example UPDATE
-- Run an example update.
UPDATE
[dbo].[table1]
SET
[tagpath] = CONCAT('cloud', SUBSTRING([source].[tagpath], 11, 128))
FROM
[dbo].[table1] AS [source] INNER JOIN
(
SELECT
DISTINCT
BINARY_CHECKSUM(SUBSTRING([tp].[tagpath], 6, 128)) AS [checksum]
FROM
[dbo].[table1] AS [tp]
WHERE
[tp].[tagpath] LIKE 'cloud/%'
) AS [reference] ON
BINARY_CHECKSUM(SUBSTRING([source].[tagpath], 11, 128)) = [reference].[checksum]
WHERE
[source].[tagpath] LIKE 'edge nodes/%';
GO
This approach means you end up with duplicate "cloud" entries. If you don't want that either, then you're looking at a DELETE statement, not an UPDATE (which introduces the additional question of which of the duplicates to keep versus delete).
Cheers,
Lain