SQL Replace only a part of a path - sql

I have a table (about 160k rows) with a column called paths.
In that column there are paths like:
"\\ab.local\folder1\folder2\folder3\folder_x"
"\\ab.local\folderA\"
The length of the paths differ.
What I would like to do is to replace only the "ab" before the .local in to "cd" and leave the rest untouched.
I have been told to use a replace function, but somehow I don't get it to work the way I want to.
I am looking for the right syntax to do this.

Declare #oldval as varchar(30) = '\\ab.local\' ;
Declare #newval as varchar(30) = '\\cd.local\' ;
update yourtable set yourfield = replace(yourfield,#oldval ,#newval) where yourfield like #oldval + '%'

Solved Reference : https://stackoverflow.com/a/814551/6923146
Hope it's perfect for your solution
UPDATE my_table
SET columnName = replace(columnName, 'oldstring', 'newstring')
WHERE columnName like '%oldstring%'
For example:
UPDATE my_table
SET columnName = replace(columnName, '\ab.', '\ab.')
WHERE columnName like '%\ab.%'

If the part to replace is on a fixed position with a fixed length you could use STUFF, like so:
UPDATE yourTable SET paths = STUFF(paths, 3, 2, 'cd')
This replaces two characters in paths beginning at position 3 with cd

Related

How to replace duplicate words in a column with just one word in SQL Server

I have a few million strings that relate to file paths in my database;
due to a third party program these paths have become nested like below:
C:\files\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\unique_bit_here\
I want update the entries so that thirdparty\thirdparty\etc becomes \thirdparty.
I have tried this code:
UPDATE table
SET Field = REPLACE(Field, 'tables\thirdparty\%thirdparty\%\', 'tables\thirdparty\')
WHILE EXISTS (SELECT * FROM table WHERE Field LIKE '%\thirdparty\thirdparty\%')
BEGIN
UPDATE table SET Field = REPLACE(Field, '\thirdparty\thirdparty\', '\thirdparty\')
END
So do you want something like this?
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\'))
You can avoid using a loop with the following technique:
Update TABLE
SET Field = left(Field,charindex('*',replace(Field, 'thirdparty\', '*'))-1)+'thirdparty\'+right(Field,charindex('*',reverse(replace(Field, 'thirdparty\', '*')))-1)
Its too late, but I just guess if I want replace a single word in repeating multiple time same word as he want. This will replace all with append a single time '\thirdparty'...
Check this.
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

updating a text with additional characters in SQL

I have the following value format :
1234567890
I want to convert it to the following format : 123-45A67890
Table Name: Test
Column Name : MyCode
Note that I am using Microsoft SQL 2012.
You can use STUFF . Something like this
DECLARE #v VARCHAR(15) = '1234567890'
SELECT STUFF(STUFF(#v,4,0,'-'),7,0,'A')
Your SELECT would be
SELECT STUFF(STUFF(MyCode,4,0,'-'),7,0,'A')
FROM Test
Your UPDATE would be
UPDATE Test
SET MyCode = STUFF(STUFF(MyCode,4,0,'-'),7,0,'A')
Does SQL Server support the PASTE function?
paste(paste('1234567890',7,0,'A'),4,0,'-')
For example:
select paste(paste(column_name,7,0,'A'),4,0,'-') from table_name
or
update table_name set column_name = paste(paste(column_name,7,0,'A'),4,0,'-')
Here what tried with a variable #a:
declare #a varchar(100)='1234567890'
select STUFF(STUFF(#a,4,0,'-'),7,0,'A') --gives--> '123-45A67890'
Likely you can use it to update your table, which
Adds Hyphen (-) after first 3rd character,
Adds letter 'A' after 2 letters just after hyphen...
update Test set MyCode = STUFF(STUFF(MyCode,7,0,'A'),4,0,'-')
More about STUFF() function in SQL

UPDATE and REPLACE part of a string

I've got a table with two columns, ID and 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. I tried UPDATE and 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. Why is that?
You don't need wildcards in the REPLACE - it just finds the string you enter for the second argument, so the following should work:
UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <=4
If the column to replace is type text or ntext you need to cast it to nvarchar
UPDATE dbo.xxx
SET Value = REPLACE(CAST(Value as nVarchar(4000)), '123', '')
WHERE ID <=4
Try to remove % chars as below
UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <=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%'
query:
UPDATE tablename
SET field_name = REPLACE(field_name , 'oldstring', 'newstring')
WHERE field_name LIKE ('oldstring%');
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
Update Products Set Code = replace(Code, '32-', '14-') Where ...(Put your where statement in here)
For anyone want to replace your script.
update dbo.[TABLE_NAME] set COLUMN_NAME= replace(COLUMN_NAME, 'old_value', 'new_value') where COLUMN_NAME like %CONDITION%
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
you should use the below update query
UPDATE dbo.xxx SET Value=REPLACE(Value,'123\','') WHERE Id IN(1, 2, 3, 4)
UPDATE dbo.xxx SET Value=REPLACE(Value,'123\','') WHERE Id <= 4
Either of the above queries should work.
replace for persian word
UPDATE dbo.TblNews
SET keyWords = REPLACE(keyWords, '-', N'،')
help:
dbo.TblNews -- table name
keyWords -- fild name

How to replace a string in a SQL Server Table Column

I have a table (SQL Sever) which references paths (UNC or otherwise), but now the path is going to change.
In the path column, I have many records and I need to change just a portion of the path, but not the entire path. And I need to change the same string to the new one, in every record.
How can I do this with a simple update?
It's this easy:
update my_table
set path = replace(path, 'oldstring', 'newstring')
UPDATE [table]
SET [column] = REPLACE([column], '/foo/', '/bar/')
I tried the above but it did not yield the correct result. The following one does:
update table
set path = replace(path, 'oldstring', 'newstring') where path = 'oldstring'
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%'
Without the CAST function I got an error
Argument data type ntext is invalid for argument 1 of replace function.
You can use this query
update table_name set column_name = replace (column_name , 'oldstring' ,'newstring') where column_name like 'oldstring%'
all answers are great but I just want to give you a good example
select replace('this value from table', 'table', 'table but updated')
this SQL statement will replace the existence of the word "table"
(second parameter) inside the given statement(first parameter) with the third parameter
the initial value is this value from table but after executing replace function it will be this value from table but updated
and here is a real example
UPDATE publication
SET doi = replace(doi, '10.7440/perifrasis', '10.25025/perifrasis')
WHERE doi like '10.7440/perifrasis%'
for example if we have this value
10.7440/perifrasis.2010.1.issue-1
it will become
10.25025/perifrasis.2010.1.issue-1
hope this gives you better visualization
select replace(ImagePath, '~/', '../') as NewImagePath from tblMyTable
where "ImagePath" is my column Name. "NewImagePath" is temporery
column Name insted of "ImagePath" "~/" is my current string.(old
string) "../" is my requried string.(new string)
"tblMyTable" is my table in database.
you need to replace path with the help of replace function.
update table_name set column_name = replace(column_name, 'oldstring', 'newstring')
here column_name refers to that column which you want to change.
Hope it will work.
If target column type is other than varchar/nvarchar like text, we need to cast the column value as string and then convert it as:
update URL_TABLE
set Parameters = REPLACE ( cast(Parameters as varchar(max)), 'india', 'bharat')
where URL_ID='150721_013359670'
You also can replace large text for email template at run time, here is an simple example for that.
DECLARE #xml NVARCHAR(MAX)
SET #xml = CAST((SELECT [column] AS 'td','',
,[StartDate] AS 'td'
FROM [table]
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
select REPLACE((EmailTemplate), '[#xml]', #xml) as Newtemplate
FROM [dbo].[template] where id = 1

What is the easiest way using T-SQL / MS-SQL to append a string to existing table cells?

I have a table with a 'filename' column.
I recently performed an insert into this column but in my haste forgot to append the file extension to all the filenames entered. Fortunately they are all '.jpg' images.
How can I easily update the 'filename' column of these inserted fields (assuming I can select the recent rows based on known id values) to include the '.jpg' extension?
The solution is:
UPDATE tablename SET [filename] = RTRIM([filename]) + '.jpg' WHERE id > 50
RTRIM is required because otherwise the [filename] column in its entirety will be selected for the string concatenation i.e. if it is a varchar(20) column and filename is only 10 letters long then it will still select those 10 letters and then 10 spaces. This will in turn result in an error as you try to fit 20 + 3 characters into a 20 character long field.
MattMitchell's answer is correct if the column is a CHAR(20), but is not true if it was a VARCHAR(20) and the spaces hadn't been explicitly entered.
If you do try it on a CHAR field without the RTRIM function you will get a "String or binary data would be truncated" error.
Nice easy one I think.
update MyTable
set filename = filename + '.jpg'
where ...
Edit: Ooh +1 to #MattMitchell's answer for the rtrim suggestion.
If the original data came from a char column or variable (before being inserted into this table), then the original data had the spaces appended before becoming a varchar.
DECLARE #Name char(10), #Name2 varchar(10)
SELECT
#Name = 'Bob',
#Name2 = 'Bob'
SELECT
CASE WHEN #Name2 = #Name THEN 1 ELSE 0 END as Equal,
CASE WHEN #Name2 like #Name THEN 1 ELSE 0 END as Similiar
Life Lesson : never use char.
I wanted to adjust David B's "Life Lesson". I think it should be "never use char for variable length string values" -> There are valid uses for the char data type, just not as many as some people think :)
The answer to the mystery of the trailing spaces can be found in the ANSI_PADDING
For more information visit: SET ANSI_PADDING (Transact-SQL)
The default is ANSI_PADDIN ON. This will affect the column only when it is created but not to existing columns.
Before you run the update query, verify your data. It could have been compromised.
Run the following query to find compromised rows:
SELECT *
FROM tablename
WHERE LEN(RTRIM([filename])) > 46
-- The column size varchar(50) minus 4 chars
-- for the needed file extension '.jpg' is 46.
These rows either have lost some characters or there is not enough space for adding the file extension.