SQL UPDATE with LIKE - mysql

I was trying to update approx 20,000 records in a table by using statements like this one,
however, I got the message say 0 row(s) affected so it didn't work.
UPDATE nc_files SET title ="Worklog details" WHERE "log_name" LIKE "%PC01%"
The log_name field has all the file names with mixed file extensions and cases ,e.g.
PC01.TXT | Worklog details
PC02.txt | Project Summary
PC03.DOC| Worklog details
PC04.doc| Project Summary
The reason why I need to use LIKE is that the updated file only have file name without extension, e.g.
PC01 | Worklog details
PC02 | Project Summary
How do I update records by using LIKE?

The log_name is a field name, remove literal quotes from it -
UPDATE nc_files SET title ="Worklog details" WHERE log_name LIKE "%PC01%"

this is because your column name log_name should not be in ' quotes.
"log_name" LIKE "%PC01%" condition will always fail and zero rows will get updated, try this:
UPDATE nc_files
SET title ="Worklog details"
WHERE log_name LIKE "%PC01%";

By default MySQL allows double quoted names to be understood as either identifiers (like column names) or as string literals.
This is meant as a convenience, but I find the semantic ambiguity frustrating. MySQL must resolve the ambiguity, and cannot magically always guess the coder's intention, as you discovered.
-- In default sql_mode under 5.5
--
SELECT "foo" -- "foo" is a *column* if tbl.foo exists, otherwise a string
FROM "tbl" -- Oops! ER_PARSE_ERROR (1064) Can't do this in default mode.
WHERE "foo" = "foo"; -- Both of these are strings
So, the way around it is to force unambiguous interpretation of identifiers:
Do not quote simple identifiers
Use MySQL-specific backticks for quoting(This is ODBC's SQL_IDENTIFIER_QUOTE_CHAR)
Always override the change the sql_mode to include ANSI_QUOTES (or a superset of it)Double quotes are then exclusively for identifiers, single quotes for strings.
#3 is my personal favorite, for readability and portability. The problem is it tends to surprise people who only know MySQL, and you have to remember to override the default.

"log_name" should not be in quotes

I had a similar trouble. The problem are the quotations marks "
I Fixed my code as follow.
UPDATE Table SET Table.Field = "myreplace"
WHERE (((Table.Field) Like '%A-16%'));
Regards, Alexwin1982

Try replace keyword
UPDATE nc_files SET title = REPLACE(title, 'PC01', 'Worklog details') WHERE log_name LIKE '%PC01%'

Related

using REPLACE in MySQL Query just isn't working

Quick background, I have a small database with a table named 'songs'. This table holds the title, artist and URL of music I have on my machine. Several of the single quotes have been dropped from the track title (for example, the don't is stored as dont) and I'm attempting to replace them. I just cannot get this query to affect any rows:
UPDATE Songs
SET Title = REPLACE (Title, 'dont', 'don\'t')
No love. Isn't this correct syntax? It tells me that 0 rows were updated.
If it helps, I'm running version 5.5.27. I know there are a couple hundred rows with improper donts in there... I'm about to dump the results into Notepad and do a find/replace on don't and just run an update statement that way, but it's kinda hacky. Any ideas friends?
A couple of sample rows:
"51","Dont Stay Home","311","311 Greatest Hits","Rap","E:\Music\311\311GreatestHits\dontstayhome.mp3"
"229","Dont Turn Around","Ace Of Base","The Very Best Of","Dance","E:\Music\AceofBase\VeryBestOf\03-ace_of_base-dont_turn_around.mp3"
The Fields in order are id, title, artist, album, genre, path
You have to do it like this
UPDATE Songs
SET Title = REPLACE(Title, 'Dont', 'Don\'t');
^ ^
The reason for that is
REPLACE(str,from_str,to_str)
Returns the string str with all occurrences of the string from_str
replaced by the string to_str. REPLACE() performs a case-sensitive
match when searching for from_str.
If you want to replace either case you can do
UPDATE Songs
SET Title = REPLACE(REPLACE(Title, 'Dont', 'Don\'t'), 'dont', 'don\'t')
WHERE Title LIKE '%dont%' -- it makes sense to limit update to only those rows that have dont in it no matter case
Here is SQLFiddle demo
The first thought is that there might be some invisible characters. What does the following return?
select *
from songs
where title like '%dont%';
EDIT:
I didn't notice this at first. The problem is the space after the function name. Try this:
UPDATE Songs
SET Title = REPLACE(Title, 'dont', 'don\'t');
This is explained in the documentation:
Note
By default, there must be no whitespace between a function name and
the parenthesis following it. This helps the MySQL parser distinguish
between function calls and references to tables or columns that happen
to have the same name as a function. However, spaces around function
arguments are permitted.
EDIT II:
I don't know if the collation has an effect. But you can also try using double quotes as the string delimiter:
UPDATE Songs
SET Title = REPLACE(Title, 'dont', "don't");

removing characters from field in MS Access database table

Using MS Access 2010.
I have a field in a table that contains windows path names surrounded by quotes, like this
"C:\My Documents\Photos\img1.jpg"
"C:\My Documents\Photos\products\gizmo.jpg"
"C:\My Documents\Photos\img5.jpg"
and so on.
I need to get rid of the quotes so the column looks like this:
C:\My Documents\Photos\img1.jpg
C:\My Documents\Photos\products\gizmo.jpg
C:\My Documents\Photos\img5.jpg
Is there a way to write an update query to do this?
OR a better way to do it altogether?
If you will be doing this from within an Access session, using Access 2000 or later, you can use the Replace() function in an update query to remove the quotes. Remove would mean replace them with an empty string.
UPDATE YourTable
SET path_field = Replace(path_field, '"', '');
If any of those path strings could include quotes within them (yuck!), consider the Mid() function ... ask it to start at the 2nd character (skipping the lead quote), and return the number of characters equivalent to Len(path_field) - 2
UPDATE YourTable
SET path_field = Mid(path_field, 2, Len(path_field) - 2);
Either way, you may want to include a WHERE clause to ignore rows without path_field values.
WHERE Len(path_field) > 0
And if you must do this again when new data is added, use a different WHERE clause to ensure you UPDATE only those rows whose path_field values start and end with quotes.
WHERE path_field Like '"*"'
That was using the * wild card for Access' default ANSI 89 mode. If you will do this from ADO (ANSI 92 mode), use the % wild card.
WHERE path_field Like '"%"'
... or use ALike and the % wild card with either mode.
WHERE path_field ALike '"%"'
The solution with REPLACE already mentioned by others works, but removes ALL quotes, even if they are in the middle of the string.
If you only want to remove quotes at the beginning or at the end, but leave quotes in the middle of the string as they are, you can do it with the following two queries:
Remove first character if it's a quote:
update YourTable
set YourField = right(YourField, len(YourField) - 1)
where left(YourField, 1) = '"'
Remove last character if it's a quote:
update YourTable
set YourTable = left(YourField, len(YourField) - 1)
where right(YourField, 1) = '"'
To make this a permanent change, you might run an update query that looked something like this:
UPDATE [Your Table]
SET [Your Table].[Your Field] = Replace([Your Table].[Your Field],"""","")
This will get rid of all quotes, even if they aren't at the beginning or end. Post back if that's not exactly what you want.
Assuming your column name is MyColumn and table name is MyTable, you can use this sql to update your data to get rid of quotes.
UPDATE MyTable
SET MyColumn = REPLACE(MyColumn,'"','')

Creating variables and reusing within a mysql update query? possible?

I am struggling with this query and want to know if I am wasting my time and need to write a php script or is something like the following actually possible?
UPDATE my_table
SET #userid = user_id
AND SET filename('http://pathto/newfilename_'#userid'.jpg')
FROM my_table
WHERE filename
LIKE '%_%' AND filename
LIKE '%jpg'AND filename
NOT LIKE 'http%';
Basically I have 700 odd files that need renaming in the database as they do not match the filenames as I am changing system, they are called in the database.
The format is 2_gfhgfhf.jpg which translates to userid_randomjumble.jpg
But not all files in the database are in this format only about 700 out of thousands. So I want to identify names that contain _ but don't contain http (thats the correct format that I don't want to touch).
I can do that fine but now comes the tricky bit!!
I want to replace that file name userid_randomjumble.jpg with http://pathto/filename_userid.jpg So I want to set the column user_id in that row to a variable and insert it into my new filename.
The above doesn't work for obvious reasons but I am not sure if there is a way round what I'm trying to do. I have no idea if it's possible? Am I wasting my time with this and should I turn to PHP with mysql and stop being lazy? Or is there a way to get this to work?
Yes it is possible without the php. Here is a simple example
SET #a:=0;
SELECT * FROM table WHERE field_name = #a;
Yes you can do it using straightforward SQL:
UPDATE my_table
SET filename = CONCAT('http://pathto/newfilename_', userid, '.jpg')
WHERE filename LIKE '%\_%jpg'
AND filename NOT LIKE 'http%';
Notes:
No need for variables. Any columns of rows being updated may be referenced
In mysql, use CONCAT() to add text values together
With LIKE, an underscore (_) has a special meaning - it means "any single character". If you want to match a literal underscore, you must escape it with a backslash (\)
Your two LIKE predicates may be safely merged into one for a simpler query

MySQL: REGEXP to remove part of a record

I have a table "locales" with a column named "name". The records in name always begin with a number of characters folowed by an underscore (ie "foo_", "bar_"...). The record can have more then one underscore and the pattern before the underscore may be repeated (ie "foo_bar_", "foo_foo_").
How, with a simple query, can I get rid of everything before the first underscore including the first underscore itself?
I know how to do this in PHP, but I cannot understand how to do it in MySQL.
SELECT LOCATE('_', 'foo_bar_') ... will give you the location of the first underscore and SUBSTR('foo_bar_', LOCATE('_', 'foo_bar_')) will give you the substring starting from the first underscore. If you want to get rid of that one, too, increment the locate-value by one.
If you now want to replace the values in the tables itself, you can do this with an update-statement like UPDATE table SET column = SUBSTR(column, LOCATE('_', column)).
select substring('foo_bar_text' from locate('_','foo_bar_text'))
MySQL REGEXs can only match data, they can't do replacements. You'd need to do the replacing client-side in your PHP script, or use standard string operations in MySQL to do the changes.
UPDATE sometable SET somefield=RIGHT(LENGTH(somefield) - LOCATE('_', somefield));
Probably got some off-by-one errors in there, but that's the basic way of going about it.

Removing an Appended " In front of Every Column

I found a CSV database of Cities/ZIP/GPS, and when I imported it, it added a " infront of the columns.
alt text http://www.grabup.com/uploads/58754a865eebd94c9aafaf7444b52d15.png?direct
I don't want to go in for 33,000 entries and do this manually, is there a query I can run that will remove the quotes?
i'm not a MySql expert but this should work: (based on my similar experience in Sql Server)
UPDATE table_name SET col_name = REPLACE(col_name, '"', '')
For more info on the REPLACE and other string parsing functions, see here:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
in sql server you coud do:
update mytable set state= substring(state,2,29)
change the "29" to whatever the actual length is.
I am sure mysql must have equivalent syntax.
Repeat for each field, it looks like there is only a handful of them.
As an alternative you could filter the original csv document - isn't that easier?