How to edit fields by choosing what to be edited and leaving the rest untouched - sql

I have to edit a all fields of a column. So far it is easy :D , but the problem is that the fields contains text and numbers. And I do need to replace the text only and leave the numbers untouched. What is more the text is in unicode which is making the task even harder lol. I tried to use this query but without success ..
UPDATE table_name SET field = REPLACE(field, ' ', 'My text')

If you are using Oracle/Postgresql you can use REGEX_REPLACE to replace non-digit:
UPDATE table_name
SET field = regexp_replace( field, '[^[:digit:]]', null ) ;
SqlFiddleDemo

Related

SQL REPLACE not working as expected

I have a temp table that I'm trying to eliminate all the white spaces from a specific column. However my replace isn't working at all. Here's the code I have
IF OBJECT_ID('tempdb..#attempt1temptable') IS NOT NULL
BEGIN
DROP TABLE #attempt1temptable
END
GO
CREATE TABLE #attempt1temptable
(
temp_description varchar(MAX),
temp_definition varchar(MAX)
)
INSERT INTO #attempt1temptable
SELECT graphic_description, graphic_definition
FROM graphic
UPDATE #attempt1temptable SET temp_description=REPLACE(temp_description, ' ', '')
UPDATE #attempt1temptable SET temp_description=REPLACE(temp_description, char(160), '')
--I have no idea why it won't update correctly here
select temp_description, LEN(temp_description) from #attempt1temptable
The Insert and select work as expected however it's not updating temp_description to have no white spaces. The result of the query gives me the temp_description without anything changed to it. What am I doing wrong here?
Try replacing some other whitespace characters:
select replace(replace(replace(replace(
description
,char(9)/*tab*/,'')
,char(10)/*newline*/,'')
,char(13)/*carriage return*/,'')
,char(32)/*space*/,'')
from #attemp1temptable
You are probably dealing with other characters than space. You could be dealing with tab for example.
I would suggest to copy and paste the character to remove from the actual data into your replace statement to ensure you have the right character(s).
Edit :
Also, you seem to use LEN to verify if the data was updated or not. However, keep in mind that LEN doesn't count trailing white space as character. So the count might not change even if the data was updated

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

SQL table trailing space cause errors

I had an error in my C# code and after debugging found that
this is because on entry in a table has a trailing space.
For example 'aaa '
Now in my C# code try to set a Selected values of a combo box to this(combobox as an item with value of 'aaa' and this fails.
Clearly The solution is to fix the DB 'aaa '
Now I go to DB
and do this :
Select * from mytable
where Name='aaa'
I get Name 'aaa'
Select * from mytable
where Name='aaa '
Again I get Name 'aaa'
Select len(name) from My table
where name ='aaa'
I get 3
My question is: how by querying the table I know it has an extra space for 'aaa '?
SQL server len function excludes trailing blanks.
Consider using the DATALENGTH (Transact-SQL) function which does not trim the string.
So you can check if datalength(column) <> datalength(rtrim(column)) to find if it contains trailing spaces.
Note: if processing a unicode string, DATALENGTH will return twice the number of characters.
As Giorgi Nakeuri has explained, 'a ' and 'a' are considered equal. But you can easily find trailing spaces with LIKE:
select * from mytable where name like '% ';
And here is how to update:
update mytable set name = rtrim(name) where name like '% ';

how to avoid reaching max size of varchar2 in concat with update

I am new to oracle. when updating a table i am using
update my_table set column_name =concat(" ' ", column_name, "viewed by xxxx")
where item_value=2.
this value is being appended whenever some one is viewing...
Now my question is How to avoid max size of varchar(2) and set if it is just 50 characters lesser than its size. I am using this in servlet
My requirement is ..If some user views the item_value of 2, his userid is to be entered in my_table by concatinating the existing values in column_name where item_value=2, in one word I dont want to loose the earlier data in field when updating and to avoid reaching the max size of the field which is varchar2(900).
If the field reaches max size then the existing data will be ovewritten by the new data else it will be a concatination to existing data.
Just use SUBSTR:
update my_table set column_name
= SUBSTR(' '' ' || column_name || 'viewed by xxxx')
, 1, 900)
where item_value=2
P.S. concat can only take 2 arguments - I've converted your code to use the simpler || concatenation operator instead.
P.P.S. string literals in Oracle are delimited by ' not "
You should create a stored procedure that you will call to update that field. It will check what the new size will be after the update, and if it is too large then perform whatever action you need to (ie. add to archive table, trim off existing data, etc.).

using trim in a select statement

I have a table, my_table, that has a field my_field. myfield is defined as VARCHAR(7). When I do:
SELECT myfield
FROM my_table;
I get what appears to be the entire 7 characters, but I only want the actual data.
I tried:
SELECT TRIM(myfield)
FROM my_table;
and several variations. But instead of getting 'abcd', I get 'abcd '.
How do I get rid of the trailing blanks?
As others have said:
trim whitespace before data enters the database ("Mop the floor...);
ensure this is not actually a column of type CHAR(7).
Additionally, add a CHECK constraint to ensure no trailing spaces ("...fix the leak.") While you are at it, also prevent leading spaces, double spaces and zero-length string e.g.
CREATE TABLE my_table
(
myfield VARCHAR(7) NOT NULL
CONSTRAINT myfield__whitespace
CHECK (
NOT (
myfield = ''
OR myfield LIKE ' %'
OR myfield LIKE '% '
OR myfield LIKE '% %'
)
)
);-
VARCHAR columns will not pad the string you insert, meaning if you are getting 'ABCD ', that's what you stored in the database. Trim your data before inserting it.
Make sure you are not using the CHAR datatype, which will pad your data in the way you suggest. In any case:
SELECT TRIM(myfield) FROM mytable;
will work.
Make sure also that you are not confusing the way the SQL interpreter adds padding chars to format the data as a table with the actual response.
Make sure that you are not inserting data in this column from a CHAR(7) field.
You need to trim your result when selecting as opposed to when inserting, eg:
SELECT TRIM(myfield) FROM my_table;