如何替换SQL Server表列中的字符串

Ira*_*tro 355 sql database sql-server database-administration

我有一个SQL Sever引用路径(UNC或其他)的table(),但现在路径将会改变.

在路径列中,我有很多记录,我需要更改路径的一部分,而不是整个路径.我需要在每条记录中将相同的字符串更改为新字符串.

我怎么能用简单的方法做到这一点update

cjk*_*cjk 589

就这么简单:

update my_table
set path = replace(path, 'oldstring', 'newstring')
Run Code Online (Sandbox Code Playgroud)

  • 如果有很多数据,我通常会添加`where'like oldstring%'. (37认同)
  • where 条件有意义,因为如果表中有 50 行,并且如果我用替换函数替换 10 行,它会影响所有 50 行,即使如果没有 where 条件它也会替换 10 行。但如果你有上面评论中提到的 where 条件,它只会影响 10 行。 (2认同)

Mar*_*ell 129

UPDATE [table]
SET [column] = REPLACE([column], '/foo/', '/bar/')
Run Code Online (Sandbox Code Playgroud)

  • 抱歉,十年后不要挑剔,但从答案中不清楚“foo”是否被替换或“bar”(再次抱歉) (5认同)

小智 25

我尝试了上述但没有产生正确的结果.以下是:

update table
set path = replace(path, 'oldstring', 'newstring') where path = 'oldstring'
Run Code Online (Sandbox Code Playgroud)

  • 也许你的意思是'像'%oldstring%'这样的路径? (11认同)
  • 这完全违背了使用替换方法的目的.你可以完成同样的事情:update table set path ='newstring'where path ='oldstring'; (10认同)

小智 17

UPDATE CustomReports_Ta
SET vchFilter = REPLACE(CAST(vchFilter AS nvarchar(max)), '\\Ingl-report\Templates', 'C:\Customer_Templates')
where CAST(vchFilter AS nvarchar(max)) LIKE '%\\Ingl-report\Templates%'
Run Code Online (Sandbox Code Playgroud)

没有这个CAST功能我得到了一个错误

参数数据类型ntext对于函数的参数1无效replace.


Nit*_*pra 9

您可以使用此查询

update table_name set column_name = replace (column_name , 'oldstring' ,'newstring') where column_name like 'oldstring%'
Run Code Online (Sandbox Code Playgroud)


Bas*_*ANI 8

所有答案都很棒,但我只想给你一个很好的例子

select replace('this value from table', 'table',  'table but updated')
Run Code Online (Sandbox Code Playgroud)

此SQL语句将使用第三个参数替换给定语句(第一个参数)中"table"(第二个参数)一词的存在

初始值是,this value from table但执行替换功能后,它将是this value from table but updated

这是一个真实的例子

UPDATE publication
SET doi = replace(doi, '10.7440/perifrasis', '10.25025/perifrasis')
WHERE doi like '10.7440/perifrasis%'
Run Code Online (Sandbox Code Playgroud)

例如,如果我们有这个值

10.7440/perifrasis.2010.1.issue-1
Run Code Online (Sandbox Code Playgroud)

它会成为

10.25025/perifrasis.2010.1.issue-1
Run Code Online (Sandbox Code Playgroud)

希望这能为您提供更好的可视化


小智 8

您需要借助替换功能来替换路径。

update table_name set column_name = replace(column_name, 'oldstring', 'newstring')
Run Code Online (Sandbox Code Playgroud)

这里column_name指的是您要更改的列。

希望它能起作用。


Dur*_*dey 6

select replace(ImagePath, '~/', '../') as NewImagePath from tblMyTable 
Run Code Online (Sandbox Code Playgroud)

其中"ImagePath"是我的列名.
"NewImagePath"是temporery列,名为"ImagePath",
"〜/"是我当前的字符串.(旧字符串)
"../"是我需要的字符串.(新字符串)
"tblMyTable"是我在数据库中的表.