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

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';

Related

How can I replace multiple words of a string in SQL

Is it possible to replace multiple words in a string in sql without using multiple replace functions?
For example I have a string where I need to replace word 'POLYESTER' with 'POLY' , 'COTTON' with 'CTN', 'GRAPHIC' with 'GRPHC' etc in order to keep the string length at a max of say 30 without much loosing the readability of contents in it(can't use substring to limit chars since it can trim the end meaningful parts of string completely). So we decided to short some keywords like above.
Current query I have used :
SELECT
REPLACE(REPLACE('**Some string value **COTTON **Some string value ** POLYESTER', 'POLYESTER', 'POLY'), 'COTTON', 'CTN')
If I have 10 keywords like this, what will be the best way to achieve the result other than using multiple replace function. I am using SQL Server 2012.
considering sql server is your only instrument (not a c# or another application), as a workaroud; use a temp or persistent table to store replacement options.
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
DROP TABLE #tmp
CREATE TABLE #tmp (
fromText VARCHAR(16),
toText VARCHAR(16)
);
INSERT INTO #tmp (fromText, toText)
VALUES
('POLYESTER', 'POLY'),
('COTTON', 'CTN'),
('GRAPHIC', 'GRPHC')
DECLARE #someValue AS NVARCHAR(MAX) =
'**Some string value **COTTON **Some string value ** POLYESTER';
SELECT #someValue = REPLACE(#someValue, fromText, toText) FROM #tmp;
PRINT #someValue
and the result is:
**Some string value **CTN **Some string value ** POLY.
The answer of mehmetx is actually very nice.
If you need your replacement functionality on a regular basis, you could think about using a normal table instead of a temporary table.
But if you need this logic only once in a while, and performance is not much of an issue, you could avoid the additional replacements table altogether and use a table expression in the FROM clause instead. Something like this:
DECLARE #someValue AS NVARCHAR(MAX) = '**Some string value **COTTON **Some string value ** POLYESTER';
SELECT #someValue = REPLACE(#someValue, fromText, toText)
FROM
(VALUES
('POLYESTER', 'POLY'),
('COTTON', 'CTN'),
('GRAPHIC', 'GRPHC')
) AS S (fromText, toText);
EDIT:
I noticed, that this logic regrettably does not work as expected when used in an UPDATE statement to update existing data in a table.
For that purpose (if needed), I created a user-defined function that performs the replacement logic. I called it MultiReplace. And it does not use the replacement data from a temporary table, but from a "normal" table, which I called Replacements.
The following code demonstrates it. It uses a data table called MyData, which gets updated with all replacements in the Replacements table using the MultiReplace function:
IF OBJECT_ID('MultiReplace') IS NOT NULL
DROP FUNCTION MultiReplace;
IF OBJECT_ID('Replacements') IS NOT NULL
DROP TABLE Replacements;
IF OBJECT_ID('MyData') IS NOT NULL
DROP TABLE MyData;
GO
CREATE TABLE Replacements (
fromText VARCHAR(100),
toText VARCHAR(100)
);
CREATE TABLE MyData (
SomeValue VARCHAR(MAX)
)
GO
CREATE FUNCTION MultiReplace(#someValue AS VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
SELECT #someValue = REPLACE(#someValue, fromText, toText) FROM Replacements;
RETURN #someValue;
END;
GO
INSERT INTO MyData (SomeValue)
VALUES
('**Some string value **COTTON **Some string value ** POLYESTER');
INSERT INTO Replacements (fromText, toText)
VALUES
('POLYESTER', 'POLY'),
('COTTON', 'CTN'),
('GRAPHIC', 'GRPHC');
SELECT * FROM MyData;
UPDATE MyData SET SomeValue = dbo.MultiReplace(SomeValue)
SELECT * FROM MyData;
But perhaps using multiple REPLACE statements might be more straightforward after all?...
EDIT 2:
Based on the short conversation in the comments, I could propose a simpler solution that uses multiple REPLACE statements in a clearer way. I have only tested it on SQL Server 2019; I am not sure if it will work correctly on SQL Server 2012.
Again, I use a table called MyData for testing here. But there are no additional database objects anymore.
Regrettably, I did not get it to work with a temporary table containing the replacement values.
-- Preparations:
IF OBJECT_ID('MyData') IS NOT NULL
DROP TABLE MyData;
CREATE TABLE MyData (
SomeValue VARCHAR(MAX)
);
INSERT INTO MyData
VALUES
('**Some string value **COTTON **Some string value ** POLYESTER'),
('**Another string value **GRAPHIC **Another string value ** POLYESTER');
-- Actual work:
SELECT * FROM MyData; -- Show the state before updating
DECLARE #someValue VARCHAR(MAX);
UPDATE MyData
SET
#someValue = SomeValue,
#someValue = REPLACE(#someValue, 'POLYESTER', 'POLY'),
#someValue = REPLACE(#someValue, 'COTTON', 'CTN'),
#someValue = REPLACE(#someValue, 'GRAPHIC', 'GRPHC'),
SomeValue = #someValue;
SELECT * FROM MyData; -- Show the state after updating

How to write an attribute name to the select query dynamically

I have a table including:
ID Name Period0Id Period1Id Period2Id
What I would like to receive data based on a user-defined parameter #check.
Lets assume:
declare #check int = 1;
In this case I need to get Period1Id value from the table. So I need to have something like that:
Select ID, Name, StatusId = Period + #check + Id -- #check is the parameter
From mytable
However, my query is not working. How can I fix this?
Your table looks like it is not in first normal form.
Instead of three columns for Period0Id to Period2Id you could have a column for PeriodIndex with values of (0,1,2) and a single column for PeriodId and then it would be just a WHERE PeriodIndex = #Check
You can't select a column using string interpolation with a variable as you are attempting. You can use dynamic SQL to create the SQL String dynamically. Or simply hardcode the options if they all have the same dataype.
Select ID,
Name,
StatusId = CASE #Check WHEN 0 THEN Period0Id
WHEN 1 THEN Period1Id
WHEN 2 THEN Period2Id
END
From mytable
Here is an alternative way that will create dynamic columns, which is essentially using your original query:
DECLARE #check VARCHAR = 1
DECLARE #sqlquery NVARCHAR(MAX)
SET #sqlquery = N'SELECT ID, Name, StatusId = Period'+#check+'Id
FROM mytable'
EXEC sp_executesql #sqlquery

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

Replace Any Occurrence of "P" in String With A Value From Another Table

I have a column, sort_order in a table that contains a string of numbers, a delimiter and some P values:
1150||P||1168||1144||1149||1147||1164||1152||P||1148||1162||1163||P||1156||1157||1154||
I would like to replace any P values in this string with another value from the event_tile_id column of another table.
So far I've drafted this SQL below with no luck. What changes can I make to this Query to get the effect I need?
`SELECT sort_order,
(
REPLACE(sort_order,'P',
(SELECT TOP 1 event_tile_id
FROM daily_email_sales_today)
)
)
as sort_order
FROM daily_email_preview`
Removed "default_SaleID" from Query. Replace should now have 4 arguments.
This is how I would do it.
Since you don't have any joins, why not do a simpler update query using a static value?
DECLARE #update VARCHAR(100)
SET #update = (SELECT TOP 1 event_tile_id FROM daily_email_sales_today)
update daily_email_preview
SET sort_order = replace(sort_order,'P', #update)
Or even,
update daily_email_preview
SET sort_order = replace(sort_order,'P', '<new value>')
Assuming you are using SQL Server.
Along the same thought process as #Eric_Hauenstein if you are running this in a TSQL process:
declare #rSTR as varchar(50)
SELECT TOP 1 #rSTR = event_tile_id FROM daily_email_sales_toda
SELECT sort_order, REPLACE(sort_order,'P', #rSTR) as sort_order
FROM daily_email_preview

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