我正在将一个数据库从一个服务器移动到另一个服务器,其中有很多序列化数据。所以,我想知道:
是否可以使用regex替换所有出现的事件,如以下(和类似)

s:22:\"http://somedomain.com/\"
s:26:\"http://somedomain.com/abc/\"
s:29:\"http://somedomain.com/abcdef/\"


s:27:\"http://someOtherdomain.com/\"
s:31:\"http://someOtherdomain.com/abc/\"
s:34:\"http://someOtherdomain.com/abcdef/\"

最佳答案

如果包含这些数据的列具有相同的长度,并且这些22, 26, 29,...出现在字符串开头的相同位置。然后,对于SQL Server,可以使用REPLACESUBSTRINGCHARINDEX来执行以下操作:

DECLARE @s VARCHAR(50);
DECLARE @sub INT;
SET @s = 's:27:\"http://somedomain.com/\"';
SET @sub = CONVERT(INT, SUBSTRING(@s, CHARINDEX(':', @s) + 1, 2));
SELECT REPLACE(REPLACE(@s, 'somedomain', 'someOtherdomain'), @sub, @sub + 5);

因此s:number:\"http://somedomain.com/\"将变成s:number + 5:\"http://someOtherdomain.com/\"
如果要对该表运行UPDATE,可以这样编写:
UPDATE @t
SET s = REPLACE(REPLACE(s, 'somedomain', 'someOtherdomain'),
            CONVERT(INT, SUBSTRING(s, CHARINDEX(':', s) + 1, 2)),
            CONVERT(INT, SUBSTRING(s, CHARINDEX(':', s) + 1, 2)) + 5);

这个查询的作用是,它搜索somedomain的出现并用someOtherdomain替换它,得到前两个:之间的数字,将其转换为INT并用相同的数字替换它。以下是运行上一个查询后数据的外观:
s:27:\"http://someOtherdomain.com/\"
s:31:\"http://someOtherdomain.com/abc/\"
s:34:\"http://someOtherdomain.com/abcdef/\"

这是一个Live Demo

关于sql - 搜索并替换序列化的数据库转储,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12446027/

10-17 00:44
查看更多