天天看点

字符串的UPDATE和REPLACE部分

本文翻译自:UPDATE and REPLACE part of a string

I've got a table with two columns,

ID

and

Value

.

我有一个包含两列的表,

ID

Value

I want to change a part of some strings in the second column.

我想在第二列中更改某些字符串的一部分。

Example of Table:

表示例:
ID            Value
---------------------------------
1             c:\temp\123\abc\111
2             c:\temp\123\abc\222
3             c:\temp\123\abc\333
4             c:\temp\123\abc\444
           

Now the

123\\

in the

Value

string is not needed.

现在,不需要

Value

字符串中的

123\\

I tried

UPDATE

and

REPLACE

:

我尝试了

UPDATE

REPLACE

UPDATE dbo.xxx
SET Value = REPLACE(Value, '%123%', '')
WHERE ID <= 4
           

When I execute the script SQL Server does not report an error, but it does not update anything either.

当我执行脚本时,SQL Server不会报告错误,但也不会更新任何内容。

Why is that?

这是为什么?

#1楼

参考:https://stackoom.com/question/1ArUE/字符串的UPDATE和REPLACE部分

#2楼

Try to remove

%

chars as below

尝试如下删除

%

字符
UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <=4
           

#3楼

You don't need wildcards in the

REPLACE

- it just finds the string you enter for the second argument, so the following should work:

您不需要在

REPLACE

通配符-它只需查找您为第二个参数输入的字符串,因此以下代码应该起作用:
UPDATE dbo.xxx
SET Value = REPLACE(Value, '123\', '')
WHERE ID <=4
           

(I also added the

\\

in the replace as I assume you don't need that either)

(我还在替换中添加了

\\

,因为我假设您也不需要)

#4楼

To make the query run faster in big tables where not every line needs to be updated, you can also choose to only update rows that will be modified:

为了使查询在不需要更新每一行的大表中更快地运行,您还可以选择仅更新将要修改的行:
UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <= 4
AND Value LIKE '%123%'
           

#5楼

You have one table where you have date Code which is seven character something like

您在一张桌子上有日期代码,它是七个字符,类似于
"32-1000"
           

Now you want to replace all

现在您要替换所有
"32-"
           

With

"14-"
           

The SQL query you have to run is

您必须运行的SQL查询是
Update Products Set Code = replace(Code, '32-', '14-') Where ...(Put your where statement in here)
           

#6楼

CREATE TABLE tbl_PersonalDetail
(ID INT IDENTITY ,[Date] nvarchar(20), Name nvarchar(20), GenderID int);

INSERT INTO Tbl_PersonalDetail VALUES(N'18-4-2015', N'Monay', 2),
                                     (N'31-3-2015', N'Monay', 2),
                                     (N'28-12-2015', N'Monay', 2),
                                     (N'19-4-2015', N'Monay', 2)

DECLARE @Date Nvarchar(200)

SET @Date = (SELECT [Date] FROM Tbl_PersonalDetail WHERE ID = 2)

Update Tbl_PersonalDetail SET [Date] = (REPLACE(@Date , '-','/')) WHERE ID = 2