简体   繁体   中英

How to update text using “regular expressions” in SQL Server?

In a column in a SQL Server database table, the value has a format of X=****;Y=****;Z=5**** , where the asterisks represent strings of any lengths and of any values. What I need to do is to change that 5 to a 4 and keep the rest of the string unchanged.

Is there a way to use something like regular expressions to achieve what I want to do? If not using regular expressions, can it be done at all?

MS SQL sadly doesn't have any built in regex support (although it can be added via CLR) but if the format is fixed so that the part you want to change is Z=5 to Z=4 then using REPLACE should work:

REPLACE(your_string,'Z=5','Z=4')

For example:

declare @t table (str varchar(max))
insert @t values 
('X=****;Y=****;Z=5****'),
('X=****;Y=**df**;Z=3**sdf**'),
('X=11**;Y=**sdfdf**;Z=5**')

update @t
set str = replace(str,'Z=5','Z=4')

-- or a slightly more ANSI compliant and portable way
update @t
set str = SUBSTRING(str,0, CHARINDEX('Z=5', str)) + 'Z=4' + SUBSTRING(str, CHARINDEX('Z=5', str)+3,LEN(str))


select * from @t

str:
X=****;Y=****;Z=4****
X=****;Y=**df**;Z=3**sdf**
X=11**;Y=**sdfdf**;Z=4**

We need more information. Under what circumstances should 5 be replaced by 4? If it's just where it occurs as the first character after the Z=, then you could simply do...

set Col = Replace(Col,'Z=5','Z=4')

Or, do you just want to replace 5 with 4 anywhere in the column value. In which case you'd obviously just do...

set Col = Replace(Col,'5','4')

Or possibly you mean that 5's should be replaced by 4's anywhere within the value after Z= which would be a lot harder.

update Table set Field = replace(Field, ';Z=5', ';Z=4')

并希望您的星号数据不包含分号和等号...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM