<
在给定的数据库列中替换所有 '<' 的最佳方法是什么?基本执行s/<[^;]/</gi
笔记:
- 必须在MS SQL Server 2000中工作
- 必须是可重复的(并且不能以 结尾
<;;;;;;;;;
)
<
在给定的数据库列中替换所有 '<' 的最佳方法是什么?基本执行s/<[^;]/</gi
笔记:
<;;;;;;;;;
)需要一些黑客攻击,但我们可以使用LIKE、PATINDEX、LEFT AND RIGHT和良好的旧字符串连接来做到这一点。
create table test
(
id int identity(1, 1) not null,
val varchar(25) not null
)
insert into test values ('< <- ok, < <- nok')
while 1 = 1
begin
update test
set val = left(val, patindex('%<[^;]%', val) - 1) +
'<' +
right(val, len(val) - patindex('%<[^;]%', val) - 2)
from test
where val like '%<[^;]%'
IF @@ROWCOUNT = 0 BREAK
end
select * from test
更好的是,这与 SQL Server 版本无关,应该可以正常工作。
我认为如果你使用不同的东西,这可以做得更干净:)
create table test
(
id int identity(1, 1) not null,
val varchar(25) not null
)
insert into test values ('< <- ok, < <- nok')
WHILE 1 = 1
BEGIN
UPDATE test SET
val = STUFF( val , PATINDEX('%<[^;]%', val) + 3 , 0 , ';' )
FROM test
WHERE val LIKE '%<[^;]%'
IF @@ROWCOUNT = 0 BREAK
END
select * from test
怎么样:
UPDATE tableName
SET columName = REPLACE(columName , '<', '<')
WHERE columnName LIKE '%lt%'
AND columnName NOT LIKE '%lt;%'
编辑:
我刚刚意识到这将忽略具有部分正确<
字符串的列。
在这种情况下,您可以忽略 where 子句的第二部分,然后调用它:
UPDATE tableName
SET columName = REPLACE(columName , '<;', '<')
如果 MSSQL 的正则表达式支持负前瞻,那将是解决此问题的正确方法。
s/<(?!;)/</gi
将捕获<的所有实例,这些实例后面没有; (即使它们后面没有任何内容,[^;]会错过)并且不捕获以下非; 字符作为匹配的一部分,消除了关于该字符在替换中丢失的原始问题的评论中提到的问题。
不幸的是,我不使用 MSSQL,所以我不知道它是否支持负前瞻...
非常具体到这种模式,但我过去做过类似的事情:
REPLACE(REPLACE(columName, '<', '<'), '<', '<')
更广泛的示例(编码可能在 TITLE 属性中不合适的字符)
REPLACE(REPLACE(REPLACE(REPLACE(
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
columName
-- Remove existing encoding:
, '&', '&')
, '"', '"')
, ''', '''')
-- Reinstate/Encode:
, '&', '&')
-- Encode:
, '"', '"')
, '''', ''')
, ' ', '%20')
, '<', '%3C')
, '>', '%3E')
, '/', '%2F')
, '\', '%5C')