SQL server trimming string - sql

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)),'')

Related

SQL Server removing necessary whitespaces

I'm trying to add whitespaces to a column. However, the SPACE function is not working.
Example:
SELECT LEN(('ABC' + SPACE(10)))
Returns 3 instead 13.
This behavior also happens with the REPLICATE function.
Example:
REPLICATE(' ', 5)
Returns ''
What I need:
REPLICATE(' ', 5)
Returns ' '
Editing:
This suggestion works, but it needs do add : to the string.
DECLARE #Test varchar(32);
SELECT #Test = 'ABC' + SPACE(10);
SELECT #Test + ':';
Returns ABC :
I need ABC
--This table is in SQL Server
CREATE TABLE Iten
(
Code varchar(35)
);
--This table is on DB2
CREATE TABLE Product
(
code char(35),
description varchar(100)
)
INSERT INTO Iten VALUES ('ABC');
INSERT INTO Product VALUES ('ABC', 'My Test')
SELECT
Iten.Code, Product.description,
DATALENGTH(Iten.Code),
DATALENGTH(Product.code)
FROM
Iten
INNER JOIN
IBMServerD.DatabaseD.LDAT.Product AS Product ON Iten.Code = Product.code
This query returns no rows.
Because that, I need to fill spaces on the right to Iten.Code, but it does not respect it.
If both tables were in SQL Server, it would work fine.
Try using trim functions
SELECT Iten.Code, Product.description, DataLength(Iten.Code),
DataLength(Product.code)
from Iten INNER JOIN IBMServerD.DatabaseD.LDAT.Product as Product
ON ltrim(rtrim(Iten.Code)) = ltrim(rtrim(Product.code))
'ABC' + REPLICATE(' ',10)
works
SPACE(INTEGER) is working fine
select LEN('abc'+SPACE(10)) `3`
LEN() function excludes trailing blanks/whitespaces
select DATALENGTH('abc'+SPACE(10)) `13`
using DATALENGTH() give you 13, DATALENGTH() includes trailing blanks/whitespaces

Inserting space between the string (SQL Server)

I have a table called Manufacturers which contains a column Name with a data type of Varchar(100) that has 5761 entries such as XYZ(XYZ Corp).
I wish to insert a space between the Z and the (.
I have seen the STUFF and LEFT commands but can't seem to figure out if they apply to my scenario.
You can try the REPLACE (Transact-SQL)
function as shown below.
update <yourTableName>
set <yourColumName> = replace(<yourColumName>, '(', ' ( ')
where <put the conditions here>
Here is an implementation to you.
create table test (Name varchar(20))
insert into test values ('XYZ(XYZ Corp)')
--selecting before update
select * from test
--updating the record
update test
set Name = replace(Name, '(', ' (')
where name like '%(%' --Here you can add the conditions as you want to restrict the number of rows to be updated based on the available data or the patterns.
--selecting after update
select * from test
Live Demo
I would recommend:
update Manufacturers
set name = replace(name, '(', ' (')
where name like '%[^ ](%';
This will only update rows where there is not already a space before the open paren.
Note: If you have multiple open parens, it will update all of them. If that is an issue, ask a new question with appropriate sample data.

How to replace underscore with a blank space with a regular expression in SQL

I'm trying to insert post codes into my database but getting rid of the underscores.
I have a table called FeedDataSetMapping that is used to map the fields before they get inserted:
INSERT INTO FeedDataSetMapping (
[source_field]
,[database_field]
,[template_id]
,[conversion_id]
,[order_id]
,[values_group]
,[direct_value]
,[value_regex]
,[condition_regex]
,[split_separator]
,[enclosing_character]
,[cumulative_field]
,[cumulative_format])
VALUES
('manufacturerId','manufacturer_Id',#template_id,0,0,null,null,null,null,null,null,null,null),
('dealership','leasing_broker_name',#template_id,0,0,null,null,null,null,null,null,null,null),
('manufacturersDealerId','supplier_ref',#template_id,0,0,null,null,19,null,null,null,null,null),
('address1','address1',#template_id,0,0,null,null,null,null,null,null,null,null),
('address2','address2',#template_id,0,0,null,null,null,null,null,null,null,null),
('postcode','post_code',#template_id,0,0,null,null,null,null,null,null,null,null),
('telephone','telephone',#template_id,0,0,null,null,null,null,null,null,null,null),
('fax','fax_number',#template_id,0,0,null,null,null,null,null,null,null,null),
('email','email',#template_id,0,0,null,null,null,null,null,null,null,null),
('website','web_address',#template_id,0,0,null,null,null,null,null,null,null,null),
('NewCarSales','service_mask',#template_id,0,0,null,1,null,'^(?!(?i:^0$|^n$|^no$|^f$|^false$|^$))',null,null,1,null),
('UsedCarSales','service_mask',#template_id,0,0,null,2,null,'^(?!(?i:^0$|^n$|^no$|^f$|^false$|^$))',null,null,1,null),
('Servicing','service_mask',#template_id,0,0,null,8,null,'^(?!(?i:^0$|^n$|^no$|^f$|^false$|^$))',null,null,1,null),
('Repairs','service_mask',#template_id,0,0,null,16,null,'^(?!(?i:^0$|^n$|^no$|^f$|^false$|^$))',null,null,1,null),
('Longitude','longitude',#template_id,0,0,null,null,null,null,null,null,null,null),
('Latitude','latitude',#template_id,0,0,null,null,null,null,null,null,null,null)
This already contains some condition regex that in case that this field contains some text it converts it to true or false respectively.
What I need is a condition_regex that gets rid of these underscores and replaces it with a blank space i.e: 'GDB_A45' to 'GDB A45'. I don't know much about regex so any idea would be greatly appreciated. Thanks in advance!
SQL Server does not have much of regular expression support, but in this case I don't think you need it. You can do a simple replace:
UPDATE mytable
SET mycolumn = REPLACE(mycolumn, '_', ' ')
WHERE mycolumn LIKE '%[_]%'
To do this while updating you can use INSERT ... SELECT instead of INSERT ... VALUES:
INSERT INTO mytable (mycolumn)
SELECT REPLACE('my data 1', '_', ' ') UNION
SELECT REPLACE('my data 2', '_', ' ') UNION
SELECT REPLACE('my_data_3', '_', ' ') UNION
...
There will be some maximum number of unions you can do, so you should split your inserts into batches with this method.
Or, you could define a trigger on the target table that will do the job for you:
CREATE TRIGGER mytrigger ON mytable
AFTER INSERT AS
BEGIN
UPDATE mytable
SET mytable.mycolumn = REPLACE(i.mycolumn, '_', ' ')
FROM mytable
INNER JOIN inserted i
ON i.id = mytable.id
AND i.mycolumn LIKE '%[_]%'
END
... where it is assumed your table has a primary key named id.
Well after been thinking a while I got to the conclusion that would be easier if I replace the underscore from the scraped data during the scraping (in the c# code) before I generate the XML file. That would avoid me a lot of headaches. Anyway thank you for your help guys ;)

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

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