天天看點

字元串的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