UPDATE and REPLACE part of a string - sql

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

Related

loop to Select a record value into variable then CONCAT a value onto first variable and then update that record

Trying to update a SQL value with a concatenated value. Example, existing table has column named PONumber. Some numbers are stored by users as 4444 and some are stored as 4444.00. We want to update all the numbers listed as 4444 with the appended .00. I have the variables worked out and the concatenate worked out and binding the two together. I am just lost on the loop of getting and then updating it back. I am assuming I need a temp table for this or can I just use a set of variables for the old number, appending value, and new number?
DECLARE #ponumb nvarchar(255)
DECLARE #append nvarchar(255) = '-00'
DECLARE #BIND nvarchar(255) = CONCAT (#ponumb, #append)
CREATE TEMPORARY TABLE IF NOT EXISTS cache (SELECT #ponumb = PONumber FROM TABLE1 where PONumber not like '%-00%');
UPDATE TABLE1 SET PONumber=#BIND WHERE PONumber IN (SELECT PONumber FROM cache);
END;
Need to update the PONumbers to all have a trailing -00
Is this what you want to do?
UPDATE TABLE1
SET PONumber = PONumber + '.00'
WHERE PONumber NOT LIKE '%.00';

SQL server trimming string

I have a query, I want to Trim a column and get the only Right side values:
Here in the pic the result is like SubAccountCode and SubaccountName but user has entered code and name in SubaccountName. I want to trim the codes from Subaccountname and update the table. T
The query I have tried is mentioned below, but I think it's not so working:
Select Substring(Subaccountname,8,20)as Name from #temp
There are several ways to do this.
When looking at your example data the easiest way would be using an replace() in the update statement.
Syntax:
REPLACE ( string_expression , string_pattern , string_replacement )
Example:
UPDATE table_name
SET column2 = replace([column2], [column1], '')
What this does it updates the column2 with the value from column2 where the value from column1 is replaced with '' nothing. In your example this does leave you with an unwanted space in front. You could trim this or try as followed:
UPDATE Test
SET [SubAccountName] = replace([SubAccountName], [SubAccountCode] + ' ', '')
If the SubAccountCode could be different from the code in the SubAccountName and you only want to remove the first 8 characters (if you are sure it is always the first 8) you can use:
UPDATE YourTable SET SubAccountName = RIGHT(SubAccountName, LEN(SubAccountName) - 7)
Example script:
create table test (
SubAccountName varchar(100),
SubAccountCode varchar(100)
)
insert into test (SubAccountCode, SubAccountName) VALUES
(1234567, '1234567 AUBC' ),
(1234467, '1234467 AUBC' ),
(1235567, '1235567 AUBC' )
select * from test -- Check that the data is like your example.
UPDATE Test SET SubAccountName = RIGHT(SubAccountName, LEN(SubAccountName) - 8)
select * from test -- Check that the result is like your wanted result.
drop table test -- Cleanup the test table.
This code will work for you.
UPDATE TableName SET SubaccountName = REPLACE(LTRIM(RTRIM(SubaccountName)),LTRIM(RTRIM(SubAccountCode)),'')

concat with left in sql

i have two columens in the same table:
Column A :abcdef
Column B :12345
I want Column A value to be replaced by :
abcdef123
therefore i want all the data from column A plus the 3 first digit from column B.
I am stuck big time. I use Microsft SQL server Mgt Studio.
any help is welcome.
thanks
try this
set ColumnA=(select CONCAT(ColumnA,LEFT(ColumnB,3)))
as simple as this:
update table set ColumnA = ColumnA + LEFT(ColumnB, 3)
Use LEFT string function :
DECLARE #colA VARCHAR(100) = 'abcdef'
DECLARE #colB VARCHAR(100) = '12345'
SELECT #colA + LEFT(#colB,3)
Update Table_name SET ColumnA = ColumnA+LEFT(ColumnB,3)

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

SQL - "incrementing" a char value causes collation error

I'm dealing with a table in which a bunch of arbitrary settings are stored as VARCHAR(255) values. The particular one I'm tasked with dealing with is a sequence number that needs to be incremented and returned to the caller. (Again, note that the sequence "number" is stored as VARCHAR, which is something I don't have any control over).
Because it's a sequence number, I don't really want to select and update in separate steps. When I've dealt with this sort of thing in the past with actual numeric fields, my method has been something like
UPDATE TABLE SET #SEQ_NUM = VALUE = VALUE + 1
which increments the value and gives me the updated value in one swell foop. I thought in this situation, I'd try the same basic thing with casts:
DECLARE #SEQ_NUM VARCHAR(255)
UPDATE SOME_TABLE
SET #SEQ_NUM = VALUE = CAST((CAST(VALUE AS INT) + 1) AS VARCHAR)
WHERE NAME = 'SOME_NAME'
The actual update works fine so long as I don't try to assign the result to the variable; as soon as I do, I receive the following error:
Msg 549, Level 16, State 1, Line 4 The collation
'SQL_Latin1_General_CP1_CI_AS' of receiving variable is not equal to
the collation 'Latin1_General_BIN' of column 'VALUE'.
I understand what that means, but I don't understand why it's happening, or by extension, how to remedy the issue.
As an aside to fixing the specific error, I'd welcome suggestions for alternative approaches to incrementing a char sequence "number".
From one of the comments, sounds like you may have already hit on this, but here's what I would recommend:
UPDATE TABLE
SET VALUE = CAST((CAST(VALUE AS INT) + 1) AS VARCHAR)
OUTPUT inserted.VALUE
WHERE NAME = 'SOME_NAME'
This will output the new value like a SELECT statement does. You can also cast inserted.VALUE to an int if you wanted to do that in the SQL.
If you wanted to put the value into #SEQ_NUM instead of outputing the value from the statement/stored procedure, you can't use a scalar variable, but you can pump it into a table variable, like so:
DECLARE #SEQ_NUM AS TABLE ( VALUE VARCHAR(255) );
UPDATE TABLE
SET VALUE = CAST((CAST(VALUE AS INT) + 1) AS VARCHAR)
OUTPUT inserted.VALUE INTO #SEQ_NUM ( VALUE )
WHERE NAME = 'SOME_NAME'
SELECT VALUE FROM #SEQ_NUM
Maintaining a sequential number manually is by no means a solution I'd like to work with, but I can understand there might be constraints around this.
If you break it down in to 2 steps, then you can work around the issue. Note I've replaced your WHERE clause for this example code to work:
CREATE TABLE #SOME_TABLE ( [VALUE] VARCHAR(255) )
INSERT INTO #SOME_TABLE
( VALUE )
VALUES ( '12345' )
DECLARE #SEQ_NUM VARCHAR(255)
UPDATE #SOME_TABLE
SET [VALUE] = CAST(( CAST([VALUE] AS INT) + 1 ) AS VARCHAR(255))
WHERE 1 = 1
SELECT *
FROM #SOME_TABLE
SELECT #SEQ_NUM = [VALUE]
FROM #SOME_TABLE
WHERE 1 = 1
SELECT #SEQ_NUM
DROP TABLE #SOME_TABLE
You can continue using the quirky update in OP but you have to split the triple assignment #Variable = Column = Expression in the UPDATE statement to two simple assignments of #Variable = Expression and Column = #Variable like this
CREATE TABLE #SOME_TABLE (
NAME VARCHAR(255)
, VALUE VARCHAR(255) COLLATE Latin1_General_BIN
)
INSERT #SOME_TABLE SELECT 'SOME_NAME', '42'
DECLARE #SEQ_NUM VARCHAR(255)
/*
-- this quirky update fails on COLLATION mismatch or data-type mismatch
UPDATE #SOME_TABLE
SET #SEQ_NUM = VALUE = CAST((CAST(VALUE AS INT) + 1) AS VARCHAR)
WHERE NAME = 'SOME_NAME'
*/
-- this quirky update works in all cases
UPDATE #SOME_TABLE
SET #SEQ_NUM = CAST((CAST(VALUE AS INT) + 1) AS VARCHAR)
, VALUE = #SEQ_NUM
WHERE NAME = 'SOME_NAME'
SELECT *, #SEQ_NUM FROM #SOME_TABLE
This simple rewrite prevents db-engine complaining on difference in data-type between #Variable and Column too (e.g. VARCHAR vs NVARCHAR) and seems like a more "portable" way of doing quirky updates (if there is such thing)