如何在SQL Server中只用一个单词替换列中的重复单词

时间:2016-01-05 10:08:24

标签: sql sql-server

我有几百万个字符串与我的数据库中的文件路径有关; 由于第三方程序,这些路径已经嵌套如下:

C:\files\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\unique_bit_here\

我想更新条目,以便thirdparty\thirdparty\etc变为\thirdparty

我试过这段代码:

UPDATE table
SET Field = REPLACE(Field, 'tables\thirdparty\%thirdparty\%\', 'tables\thirdparty\')

4 个答案:

答案 0 :(得分:6)

[DataContract]
public class Person
{
    [DataMember] public string Name { get; set; }
    [DataMember] public long Size { get; set; }
    [DataMember] public DateTime Birthdate { get; set; }

    public Person(string name, long size, DateTime birthdate)
    {
        this.Name = name;
        this.Size = size;
        this.Birthdate = birthdate;
    }
}

答案 1 :(得分:2)

你想要这样的东西吗?

SELECT SUBSTRING('tables\thirdparty\%thirdparty\%\',0,CHARINDEX('\','tables\thirdparty\%thirdparty\%\',0)) + '\thirdparty\'

OR

UPDATE table
SET Field = REPLACE(Field, Field, (SELECT SUBSTRING(Field,0,CHARINDEX('\',Field,0)) + '\thirdparty\'))

答案 2 :(得分:0)

您可以避免使用具有以下技术的循环:

Update TABLE
SET Field = left(Field,charindex('*',replace(Field, 'thirdparty\', '*'))-1)+'thirdparty\'+right(Field,charindex('*',reverse(replace(Field, 'thirdparty\', '*')))-1)

答案 3 :(得分:0)

它为时已晚,但我只是猜测我是否想要在重复多次同一个单词时替换一个单词。这将取代所有人,只需追加一次' \ thirdparty' ...

检查一下。

Declare @table table(Field varchar(max))
insert into @table values('C:\files\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\unique_bit_here\')
,('C:\files\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\unique_bit_here\1')
,('C:\files\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\unique_bit_here\2')
,('C:\files\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\unique_bit_here\3')
,('C:\files\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\unique_bit_here\4')

UPDATE @table
SET Field = SUBSTRING (Field, 1, CHARINDEX('\thirdparty', Field ) ) +  'thirdparty\'
--replace (Field , 'thirdparty\' ,'')  
+ reverse( SUBSTRING ( REVERSE(Field), 1, CHARINDEX(reverse('\thirdparty'), REVERSE(Field) )-2 ) )
--REPLACE(Field, 'tables\thirdparty\%thirdparty\%\', 'tables\thirdparty\')

select * from @table