I want to generate .sql file with the sql query output . I am doing this with concat statement in sql . I am using case statement in some queries this will be the problem for me.
select concat('insert into x values(',CASE a when B then 'Book' else 'NONE' end , ') on duplicate key update B = values(B)') from author;
select 'insert into x values('+CASE a when B then 'Book' else 'NONE' end +') on duplicate key update B = values(B)' from author;
It also not works because in mysql + used for adding only numbers not for strings .
Is there any way for doing this?.
The problem with the first version is the quotes of things within the string. For instance, you want your string to contain "'Book'"
select concat('insert into x values(',
(CASE a when 'B' then '''Book''' else '''NONE''' end) ,
') on duplicate key update B = values(''B'')'
)
from author;
I think this quotes al the strings as they should be. I'm guess column A is a character that should be compared to 'B' and not to column B.
Related
I have a table which consists of 5000 rows. I need SQL command that could update each row by removing all values in "(...)" if only one couple of () is found.
Basically, if I have a name in a row:
Name surname (extra info)
I need to remove "(extra info)" and leave only Name surname
But if there is no additional couple of ()
If there is a row
Name Surname(data) (extra info)
The script should not amend this name
In simple words, I need to update a name where is only one ( or ) symbol
Many thanks
can you try to find first '(' and substring to it ?
don't forget to use case for none ( in string
update userlogin
set fullname = case position('(' in FullName)
when 0
then fullname
else substring(Fullname,1,position('(' in FullName) - 1)
end
This is an implementation of my question. I used select to let me check the result before applying it to update request. The script shows a table of
3 columns: Id, Name, UpdatedName, where Name is what we have and UpdatedName what we will obtain
SELECT `Id`,`Name`,
(case when ((LENGTH(`Name`)-LENGTH(REPLACE(`Name`, '(', ''))) = 1)
THEN
SUBSTRING_INDEX(`Name`, '(', 1)
ELSE
'-'
END)
as updated_name,
FROM table
WHERE (LENGTH(`Name`)-LENGTH(REPLACE(`Name`, '(', ''))) = 1
LIMIT 0,1500
P.S. I used Id to allow me to amend values
SELECT CASE
WHEN fname = 'correct' THEN 'your condition'
WHEN sname = 'correct' THEN 'your second condition'
ELSE 'baz'
END AS fullname
FROM `databasetable`
or you can do as like also
CASE
WHEN action = 'update' THEN
UPDATE sometable SET column = value WHERE condition;
WHEN action = 'create' THEN
INSERT INTO sometable (column) VALUES (value);
END CASE
I'm trying to append a string to an existing record in a MySQL Database:
UPDATE `db`.`tbl` SET field1 = IFNULL(field1, '') + ',' + '12/15/16: $50' WHERE field2 = 'xyz'
In MySQL, + is exactly what it suggests: addition. You are getting an error on arithmetic presumably because the strings are not converted to a number (fortunately -- otherwise you would silently get the wrong answer).
So, try this:
UPDATE `db`.`tbl`
SET field1 = CONCAT(COALESCE(field1, ''), ',', '12/15/16: $50')
WHERE field2 = 'xyz';
Or, if you don't want the comma if field1 is NULL:
UPDATE `db`.`tbl`
SET field1 = CONCAT(COALESCE(CONCAT(field1, ','), ''), '12/15/16: $50')
WHERE field2 = 'xyz';
to append in MySQL, use concat not + eg
select concat('something', 'something_else');
returns
somethingsomething_else
you can also use concat_ws (with separator)
select concat_ws('#','something', 'something_else')
returns
something#something_else
I have a sybase query that is structured like this:
SELECT
case
when isnull(a,'') <> '' then a
else convert(varchar(20), b)
end
FROM table_name
WHERE b=123
It used to return the results of the 'case' in a column named 'converted'. It now returns the results of the 'case' in a column with an empty string name ''.
How could this be? Could there be some database configuration that defaults the results of a 'case' with no name?
(I've fixed the broken query by adding " as computed" after 'end' but now I'd like to know how it used to return as 'computed' before I added the fix?)
Is this what you want?
SELECT (case when isnull(a, '') <> '' then a
else convert(varchar(20), b)
end) as converted
-------------^
FROM table_name
WHERE b = 123;
By the way, you could write the select more succinctly as:
SELECT coalesce(nullif(a, ''), b) as converted
There are two columns in a MySQL table: SUBJECT and YEAR.
I want to generate an alphanumeric unique number which holds the concatenated data from SUBJECT and YEAR.
How can I do this? Is it possible to use a simple operator like +?
You can use the CONCAT function like this:
SELECT CONCAT(`SUBJECT`, ' ', `YEAR`) FROM `table`
Update:
To get that result you can try this:
SET #rn := 0;
SELECT CONCAT(`SUBJECT`,'-',`YEAR`,'-',LPAD(#rn := #rn+1,3,'0'))
FROM `table`
You can use mysql built in CONCAT() for this.
SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;
change field name as your requirement
then the result is
and if you want to concat same field using other field which same then
SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1
then this is output
In php, we have two option to concatenate table columns.
First Option using Query
In query, CONCAT keyword used to concatenate two columns
SELECT CONCAT(`SUBJECT`,'_', `YEAR`) AS subject_year FROM `table_name`;
Second Option using symbol ( . )
After fetch the data from database table, assign the values to variable, then using ( . ) Symbol and concatenate the values
$subject = $row['SUBJECT'];
$year = $row['YEAR'];
$subject_year = $subject . "_" . $year;
Instead of underscore( _ ) , we will use the spaces, comma, letters,numbers..etc
In query, CONCAT_WS() function.
This function not only add multiple string values and makes them a single string value. It also let you define separator ( ” “, ” , “, ” – “,” _ “, etc.).
Syntax –
CONCAT_WS( SEPERATOR, column1, column2, ... )
Example
SELECT
topic,
CONCAT_WS( " ", subject, year ) AS subject_year
FROM table
I have two columns:
prenom and nom so to concatenate into a column with name chauffeur_sortant I used this script:
SELECT date as depart, retour, duree_mission, duree_utilisation, difference, observation, concat( tb_chaufeur_sortant.prenom, ' ', tb_chaufeur_sortant.nom) as chauffeur_sortant, concat(tb_chaufeur_entrant.prenom, ' ', tb_chaufeur_entrant.nom) as chauffeur_entrant
FROM tb_passation
INNER JOIN tb_vehicule
ON tb_vehicule.id = tb_passation.id_vehicule
INNER JOIN tb_chaufeur_sortant
ON tb_chaufeur_sortant.id = tb_passation.id_sortant
INNER JOIN tb_chaufeur_entrant
ON tb_chaufeur_entrant.id = tb_passation.id_entrant WHERE tb_vehicule.id = '';
$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');
I'm don't have a lot of knowledge of MySql (or SQL in general) so sorry for the noobness.
I'm trying to update a bunch of String entries this way:
Lets say we have this:
commands.firm.pm.Stuff
Well I want to convert that into:
commands.firm.pm.print.Stuff
Meaning, Add the .print after pm, before "Stuff" (where Stuff can be any Alphanumerical String).
How would I do this with a MySql Query? I'm sure REGEXP has to be used, but I'm not sure how to go about it.
Thanks
Try something like this. It finds the last period and inserts your string there:
select insert(s, length(s) - instr(reverse(s), '.') + 1, 0, '.print')
from (
select 'commands.firm.pm.Stuff' as s
) a
To update:
update MyTable
set MyColumn = insert(MyColumn, length(MyColumn) - instr(reverse(MyColumn), '.') + 1, 0, '.print')
where MyColumn like 'commands.firm.pm.%'
Perhaps use a str_replace to replace commands.firm.pm to commands.firm.pm.print
$original_str = "commands.firm.pm.15hhkl15k0fak1";
str_replace("commands.firm.pm", "commands.firm.pm.print", $original_str);
should output: commands.firm.pm.print.15hhkl15k0fak1
then update your table with the new value...How to do it all in one query (get column value and do the update), I do not know. All I can think of is you getting the column value in one query, doing the replacement above, and then updating the column with the new value in a second query.
To update rows that end in '.Stuff' only:
UPDATE TableX
SET Column = CONCAT( LEFT( CHAR_LENGTH(Column) - CHAR_LENGTH('.Stuff') )
, '.print'
, '.Stuff'
)
WHERE Column LIKE '%.Stuff'
To update all rows - by appending .print just before the last dot .:
UPDATE TableX
SET Column = CONCAT( LEFT( CHAR_LENGTH(Column)
- CHAR_LENGTH(SUBSTRING_INDEX(Column, '.', -1))
)
, 'print.'
, SUBSTRING_INDEX(Column, '.', -1)
)
WHERE Column LIKE '%.%'