INSERT INTO mySQL procedure - mysql

INSERT INTO in MySQL>
this is a part of code a procedure:
if ParentList is null then
set #sql=concat('insert into ', table_name, tabSave, '(md5Id, CommentsId, Parent, Content, UserId, Title, Nick) ',
'values(', #md5Id, ', ', CommentsId, ', null, \'', Content, '\'' ,UserId,',',Title,',',Nick, ')');
else
set #sql=concat('insert into ', table_name, tabSave, '(md5Id, CommentsId, Parent, Content, UserId, Title, Nick) ',
'values(', #md5Id, ', ', CommentsId, ', ', #Parent, ', \'', Content, '\ ,', UserId,', ', Title,', ', Nick, ')');
end if;
This character sign ' is badly inserted and I dont know where :
My error:
CALL AddDynamicTable3('asd65xb', 'xxx', 5, NULL, 'MojWstep', 22, 'New title', 'Ethan') Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '22,New title,Przemo)' at line 1
XXX - table_name
other variables are not significant example tabSave, table_name ...
Earlier I wrote the same procedure but without three variables UserId, Title, Nick and its OK but when I put this variables I only see ERROR.

See if this works:
'\ ,', UserId,',
from the second query, change to
'\ ', UserId,',

Related

select table and replace column fields by value from another table in mysql

I have been working in ms SQL from the last 3 year, I am new in MySQL, recently we have some MySQL requirement to select a table and replace column fields by value from another table.
I have converted working ms SQL query to MySQL. while executing MySQL query getting an exception. attached table description.here enter image description here
Please advise me on this.
Following are my tried queries
SET #v_Type := 'Account'; // where condition type =account
SET #select := 'SELECT';
SET #columns:= ( SELECT CONCAT('CONVERT(' , `ColDataType` , ', Col' , CONVERT(VARCHAR, `ColNum`) , ') AS [' , `ColName` , '],') FROM `Names` WHERE `TYPE` = #v_Type FOR XML PATH('') )
SET #where:='FROM `Data` WHERE [Type] = ''' + #v_Type + ''''
SET #statement = CONCAT(#select,#columns,#where);
PREPARE myStatement FROM #statement;
EXECUTE myStatement;
While executing I got the error like
Query: set #columns:= ( SELECT CONCAT('CONVERT(' , ColDataType , ', Col' , CONVERT(VARCHAR, ColNum) , ') AS [' , ColName , '],') ...
Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VARCHAR, ColNum) , ') AS [' , ColName , '],') FROM `Name' at line 2
Thanks in advance.
SELECT CONCAT( 'SELECT ', GROUP_CONCAT(CONCAT('col', colnum, ' ', colname)),
' FROM data',
' WHERE type = ?')
INTO #sql
FROM names
WHERE type = #v_type
GROUP BY type;
PREPARE myStatement FROM #sql;
EXECUTE myStatement USING #v_type;
DROP PREPARE myStatement;
fiddle

MySQL Trigger to Auto-Update (or insert) Column Field

I have an SQL query I can run that looks like:
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 1), ' ', -1) AS first_name,
If( length(name) - length(replace(name, ' ', ''))>1,
SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 2), ' ', -1) ,NULL)
as middle_name,
SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 3), ' ', -1) AS last_name
FROM people
While this is works great to split up the full name into first_name, middle_name, and last_name I need a way to have this done automatically; can't go in and run the query and manually update the table each time a person is added.
I've tried to play around with this query in the form of a trigger but keep getting errors, generally the error states "Not allowed to return a result set from trigger"
Any help getting this working would be great
In a BEFORE INSERT trigger, use the qualifier NEW. to reference values assigned to columns of the row being inserted. For example, NEW.col would reference the value supplied for the column col.
Assign a value (or expression) to NEW.col to replace the value supplied for column col, and the value assigned will be inserted instead.
A trigger to accomplish something similar to SELECT statement would look something like this:
DELIMITER $$
CREATE TRIGGER mytrigger
BEFORE INSERT ON mytable
FOR EACH ROW
BEGIN
SET NEW.first_name = SUBSTRING_INDEX(SUBSTRING_INDEX( NEW.name, ' ', 1), ' ', -1);
SET NEW.last_name = SUBSTRING_INDEX(SUBSTRING_INDEX( NEW.name, ' ', 3), ' ', -1);
SET NEW.middle_name = IF(LENGTH( NEW.name) - LENGTH(REPLACE( NEW.name, ' ', ''))>1
,SUBSTRING_INDEX(SUBSTRING_INDEX( NEW.name, ' ', 2), ' ', -1)
,NULL);
END$$
DELIMITER ;
The error you are getting:
Error: 1415 SQLSTATE: 0A000 (ER_SP_NO_RETSET)
Message: Not allowed to return a result set from a %s
Is due to a documented restriction that applies to both FUNCTION and TRIGGER. (This restriction also applies to a PROCEDURE that is called from the context of a FUNCTION or TRIGGER.)

MySql replacing spaces with hyphens

A day ago, I asked this question on stackoverflow. Sure, that works well, but does anyone know how I can do the same thing in a MySql statement without any php involved?
Eg: select preg_replace(:songName,' ', '-') //Ugh, this is wrong.
What I'm trying to do Is replace spaces with a -. But sometimes, when there is a space, I'll get more -
Eg: Metallica - Hero of the Day ends up as Metallica---Hero-of-the-Day
Any chance of making it just: Metallica-Hero-of-the-Day
BTW: It's not only song names I'm replacing.
I'm ok with a simple MySql replace, but I can see doing the above is going to need more than that.
I would replace spaces with hyphens first, then deal with any multiple hyphens that may have been created:
select replace(replace(replace(songTitle, ' ', '-'), '---', '-'), '--', '-')
I've replaced --- and -- separately because there are edge cases which overall would require both, and in that order.
See SQLFiddle
Use a user defined function like this(use delimetres accordingly)
CREATE FUNCTION replace_spaceWithHyphen(textToReplace varchar(100))
RETURNS TEXT
BEGIN
DECLARE occHyphen int;
DECLARE occSpace int;
set occHyphen = 1;
set occSpace = 1;
WHILE (occHyphen <> 0 || occSpace <> 0) DO
SELECT LOCATE('--',textToReplace) into occHyphen;
SELECT LOCATE(' ',textToReplace) into occSpace;
SELECT REPLACE(textToReplace,' ','-') into textToReplace;
SELECT REPLACE(textToReplace,'--','-') into textToReplace;
END WHILE;
RETURN textToReplace;
END;
Then call your select like this:
SELECT replace_spaceWithHyphen('Metallica - Hero of the Day');
Answer would be:
TEXT
Metallica-Hero-of-the-Day
SAMPLE FIDDLE
This should work:
select
replace(
replace(
replace('Metallica - Hero of the Day', '-', ' ')
, ' ', '')
, ' ', '-')
You may write your query. It is so easy for you.
Suppose you have a table named class(id, classname) with two fields. Now you insert in your table in classname field i.e. Metallica - Hero of the Day.
Now you can execute this by below given program.
mysql_connect('localhost','root','');
mysql_select_db('dbname'); // Please insert your dbname
$query = mysql_query('SELECT classname, REPLACE(classname," ","-") from class');
$record = mysql_fetch_array($query);
echo $record['REPLACE(classname," ","-")'];
It will give output. i.e. Metallica---Hero-of-the-Day.
and if you replace your query with. I have taken help from Bohemian answer for below query.
$query = mysql_query("SELECT classname, replace(replace(replace(classname, ' ', '-'), '---', '-'), '--', '') from class");
$record = mysql_fetch_array($query);
echo $record["replace(replace(replace(classname, ' ', '-'), '---', '-'), '--', '')"];
You will get result i.e. Metallica-Hero-of-the-Day
That's it. Easy.
Thanks
You can try this method.
UPDATE TABLE_NAME SET column_name = REPLACE(column_name, old_value, new_value);
For Example
UPDATE TABLENAME SET column_name = REPLACE(column_name, '-', ' ');
Hope this will helps you.

Modify all columns in a table to 'not null' no matter what

Is there a simple command to modify all columns in a table to not null?
Because now I have to find the name and the type of each column to write something like this:
ALTER TABLE testing CHANGE testing_text testing_text VARCHAR(10) NOT NULL;
...
and that is a lot of work for me.
A quick way is to write your alter statements into a file
select
concat('ALTER TABLE ', c.TABLE_NAME, ' CHANGE ', c.COLUMN_NAME, ' ', c.COLUMN_NAME, ' ', c.COLUMN_TYPE, ' NOT NULL;') as alter_statement
into outfile '/tmp/alter.txt'
from information_schema.COLUMNS c
where
c.IS_NULLABLE = 'YES'
and c.TABLE_SCHEMA = 'your_database_name';
Then execute the file's content
source /tmp/alter.txt
and you're done...
Tested it in a playground DB and it worked for me, still you might want to double check the file before executing :)
P.S.: I haven't checked how NULL values are handled. IIRC you have to have a default value? Not sure right now. Please test this before using it.
EDIT 1: To have one statement per table:
select
concat('ALTER TABLE ', c.TABLE_NAME, GROUP_CONCAT(' MODIFY COLUMN ', c.COLUMN_NAME, ' ', c.COLUMN_TYPE, ' NOT NULL')) as alter_statement
from information_schema.COLUMNS c
where
c.IS_NULLABLE = 'YES'
and c.TABLE_SCHEMA = 'your_database_name'
group by c.TABLE_NAME
EDIT 2:
This one works
select concat(alter_statement, ';')
into outfile '/tmp/alter.txt'
from (
select
concat('ALTER TABLE ', c.TABLE_NAME, GROUP_CONCAT(' CHANGE ', c.COLUMN_NAME, ' ', c.COLUMN_NAME, ' ', c.COLUMN_TYPE, ' NOT NULL')) as alter_statement
from information_schema.COLUMNS c
where
c.IS_NULLABLE = 'YES'
and c.TABLE_SCHEMA = 'playground'
group by c.TABLE_NAME
) sq
, but group_concat() is limited in length, so you might get syntax errors if you have too many columns in a table. Then you still have the first option from above, or you have a look at this manual entry:
The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value of max_allowed_packet. The syntax to change the value of group_concat_max_len at runtime is as follows, where val is an unsigned integer:
SET [GLOBAL | SESSION] group_concat_max_len = val;

MySQL snafoo with GROUP_CONCAT

This works:
SELECT DISTINCT HEX(group_uuid) AS hexid
FROM schema.table
>9B3D8DE01E1E049DA9F17D42B324AA66
>CDF112D740CE14EA08CA90E3C937DE8D
as does this
SELECT GROUP_CONCAT('\'', HEX(group_uuid), '\' ') AS hexid
FROM schema.table
>'9B3D8DE01E1E049DA9F17D42B324AA66','9B3D8DE01E1E049DA9F17D42B324AA66' [etc...]
and this
SELECT GROUP_CONCAT(DISTINCT HEX(group_uuid) SEPARATOR '\' ') AS hexid
FROM schema.table
>9B3D8DE01E1E049DA9F17D42B324AA66' CDF112D740CE14EA08CA90E3C937DE8D
this, however,
SELECT GROUP_CONCAT('\'', DISTINCT HEX(group_uuid), '\' ') AS hexid
FROM schema.table
Error Code: 1064. You have an error in your SQL syntax; INSERT COIN
does not.
Is there some kind 'PREFIX' keyword that can be substituted or another syntax I'm supposed to follow?
Are you looking for
GROUP_CONCAT(DISTINCT CONCAT('\'',HEX(group_uuid),'\'') SEPARATOR ' ')