Update and append unless empty - sql

Im trying to update a field by appending data to it.
if it contains the data already i wont update it otherwise I will.
if it already contains data i want it to append a comma and space followed by the word. e.g.
update myTable
set Prefixes = convert(nvarchar(max),Prefixes) + ', abc'
where MyCol='xyz' and Prefixes not like '%abc%'
im trying to get this to work so that if the prefixes column is empty initially it only includes the word 'abc'
and not ', abc'
How can i do this?

Sounds like you need a CASE:
update myTable
set Prefixes =
case
when Prefixes is null or Prefixes = ''
then 'abc'
else convert(nvarchar(max),Prefixes) + ', abc'
end
where MyCol='xyz' and (Prefixes not like '%abc%' or Prefixes is null)
See SQL Fiddle with Demo

You need to check for null values of Prefixes before filtering as NOT LIKE in the WHERE clause as well. Sql-Demo
update myTable
set Prefixes = isnull(nullif(rtrim(Prefixes),'') + ', abc','abc')
where MyCol='xyz' and isnull(Prefixes,'') not like ', abc%'

Related

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

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

Remove single characters in sql records?

I'm working on importing some files and I noticed that some of the email addresses are prefixed with a comma.
Eg: ,abc#abc.com
In a table with 1500 emails, I've found that 700+ of these have this issue.
How would I update them so that the comma is removed?
UPDATE dbo.Table
SET Email = STUFF(Email, 1, 1, '')
WHERE Email LIKE ',%';
try:
UPDATE YourTable
SET YourColumn=RIGHT(YourColumn,LEN(YourColumn)-1)
WHERE LEFT(YourColumn,1)=','
If you know they always start with a ,:
UPDATE SomeTable
SET SomeColumn = SUBSTRING(SomeColumn, 2, 4000)
WHERE SomeColumn LIKE ',%';
Otherwise you could do this to get rid of all , no matter where they appear. Note that here adding a WHERE SomeColumn LIKE '%,%' clause might adversely affect performance.
UPDATE SomeTable
SET SomeColumn = REPLACE(SomeColumn, ',', '');
UPDATE table SET email = SUBSTRING(email, 2, 1000) WHERE email LIKE ",%";
The % is a wildcard, so this will only match those fields that start with a comma.