Not Getting Value in Mysql parameter - mysql

SELECT INSTR('359616044513513-2574', '-')
I want to assign values to variables like dev=359616044513513 and id=2574
How can I do it in stored procedure of MYSQL?

Try this:
SELECT SUBSTRING_INDEX('359616044513513-2574', '-', 1),
SUBSTRING_INDEX('359616044513513-2574', '-', -1) INTO #dev, #id;

Related

Calculation within a string field MySQL

I have been attempting to edit/add a value string column (process) within a table.
The current values in the string is as follow:
1:38,25:39,41:101
What I want to do is add 1000 to every value after "X:" so after the query the values should read:
1:1038,25:1039,41:1101
I have looked at CONCAT but that seems to only insert a value into a string within certain parameters. Any ideas?
You can use CAST CONCAT and SUBSTRING_INDEX functions to get the required output, e.g.:
SELECT
CONCAT(SUBSTRING_INDEX(value, ':', 1), ":", (CAST(SUBSTRING_INDEX(value, ':', -1) AS UNSIGNED) + 1000))
FROM test;
Here's the SQL Fiddle.
Use of variables can help you achieve what you want:
select #pre := SUBSTRING_INDEX(SUBSTRING_INDEX(`column_name`, ':', 1), '0', -1),
#post := SUBSTRING_INDEX(SUBSTRING_INDEX(`column_name`, ':', 2), '0', -1),
concat(#pre,":",#post+1000) as required_value from table_name;
References:
for use of variables:
https://dev.mysql.com/doc/refman/5.7/en/user-variables.html
for substring_index:
https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring-index
You should normalize the data and store it in a separate table. That said, to answer your question you could use these queries to achieve what you want:
CREATE TEMPORARY TABLE temp (val VARCHAR(50));
SET #str = CONCAT("INSERT INTO temp (val) VALUES ('",REPLACE((SELECT org FROM mytable LIMIT 1), ",", "'),('"),"');");
PREPARE st FROM #str;
EXECUTE st;
SELECT
GROUP_CONCAT(DISTINCT CONCAT(SUBSTRING_INDEX(val, ':', 1), ":", (CAST(SUBSTRING_INDEX(val, ':', -1) AS UNSIGNED) + 1000)))
FROM temp;
Just make sure to replace SELECT org FROM mytable LIMIT 1 in the above query with your query that returns the string 1:38,25:39,41:101 you need to edit. Be aware that this example only shows how to process the value in one string. If you need to process values of multiple rows, you need to adjust a bit more...
Check sqlfiddle: http://sqlfiddle.com/#!9/bf6da4/1/0

mysql replace number value from select to another string

i would like to replace value like:
1106,1107,1108
from select query to a string link like:
http://something.com/img/1/1/0/6/1106.jpg,http://something.com/img/1/1/0/7/1107.jpg,http://something.com/img/1/1/0/8/1108.jpg
can it be done in mysql query?
Assuming the image names have variable length, I think you'll need to write a stored function to implement this natively in MySQL, there's no obvious built-in function.
The example below will take 1106 and convert it to http://something.com/img/1/1/0/6/1106.jpg. To parse multiple image IDs like 1106,1107,1108 you'd need to extend it to insert the path again every time it finds a comma, or (better) select the results out of the database in a way that is not comma-separated.
DELIMITER //
CREATE FUNCTION TO_IMAGE_PATH(id VARCHAR(255), path VARCHAR(255))
RETURNS VARCHAR(255) DETERMINISTIC NO SQL
BEGIN
DECLARE output VARCHAR(255) DEFAULT path;
DECLARE position INT DEFAULT 1;
WHILE position <= LENGTH(id) DO
SET output = CONCAT(output, SUBSTRING(id, position, 1), '/');
SET position = position + 1;
END WHILE;
SET output = CONCAT(output, id, '.jpg');
RETURN output;
END//
DELIMITER ;
SELECT TO_IMAGE_PATH('1106', 'http://something.com/img/');
-- Output: http://something.com/img/1/1/0/6/1106.jpg
You might prefer to pass in the jpg extension, or hard-code the initial path.
While this does work, this seems like an example of a problem which might be better solved in another programming language after you have selected out your results.
If all of the image IDs are exactly 4 digits long, you could do the simpler (but less elegant)
SELECT CONCAT(
'http://something.com/img/',
SUBSTRING(field_name, 1, 1), '/',
SUBSTRING(field_name, 2, 1), '/',
SUBSTRING(field_name, 3, 1), '/',
SUBSTRING(field_name, 4, 1), '/',
field_name, '.jpg');
Again, you'd need to work out how to select the values out so they aren't comma-separated. In general, if you're storing values comma-separated in your database, then you shouldn't be.

SQL Take off last character if a certain one exists in a string

I have a column with few different ID's
abc_1234
abc_2345
bcd_3456/
cde_4567/
And I want a new column that takes off the / if it exists
abc_1234
abc_2345
bcd_3456
cde_4567
I know I'll be using a combination of IF/THEN, LEFT, and LEN, but I don't know the syntax. Help is appreciated! Thanks!
(In case your are using SQL Server RDBMS)
You can try the following combination of right and left:
case when right(col, 1) = '/' then left(col, len(col)-1) else col end
SQLFiddle
(In case your are using MySQL RDBMS)
trim(trailing '/' from col);
SQLFiddle
If your using SQL Server try this
SELECT REPLACE(col,'/','')
Replace (Transact-SQL)
You would usually simply trim the string:
Oracle: select rtrim(col, '/') from ...
MySQL and PostgreSQL: select trim(trailing '/' from col) from ...
but not all DBMS offer this. SQL Server for instance doesn't.
For SQLServer
declare #tbl table
(
c1 nvarchar(9)
)
insert into #tbl values ('abc_1234')
insert into #tbl values ('abc_2345')
insert into #tbl values ('abc_3456/')
insert into #tbl values ('abc_4567/')
select IIF(RIGHT(c1, 1) = '/', LEFT(C1, LEN(C1)-1), C1)
from #tbl
Result
abc_1234
abc_2345
abc_3456
abc_4567

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: split varchar value and insert parts

I have a denormalised records in my table:
ID, CODES
1 |1|2|3|4
2 |5|6|7|8
In second column there are int values, saved in varchar field separated by | symbol.
I want to convert them to normal Many2Many relational form, using link table.
So I want to create a table like this
ID CODE
1 1
1 2
1 3
1 4
....
2 8
I understand that I can iterate through the records in mysql stored function, split string and insert value. But I am interested: is it possible to convert data this way without stored procedure/function, but using only query (create table ... select ...)?
Thanks.
UPD: There is variable number of codes in different rows. Each line has from 1 to 15 codes.
Here's how it works, inclusive test data and so on.
But consider that this is just a fun answer. The way to go is clearly a stored procedure or a function or whatever.
drop table testvar;
create table testvar (id int, codes varchar(20));
insert into testvar values (1, '|1|2|3|4'), (2, '|5|6|7|8');
drop table if exists inserttest;
create table inserttest (id int, code int);
select #sql:=left(concat('insert into inserttest values ', group_concat( '(', id, ',', replace(right(codes, length(codes) - 1), '|', concat( '),(', id, ',' )), '),' separator '')), length(concat('insert into inserttest values ', group_concat( '(', id, ',', replace(right(codes, length(codes) - 1), '|', concat( '),(', id, ',' )), '),' separator ''))) -1)
from testvar;
prepare stmt1 from #sql;
execute stmt1;
select * from inserttest;
The Oracle way is:
insert into newtestvar
select t.id, to_number(substr(t.codes, p1 + 1, p2))
from (
select testvar.id, testvar.codes, s.num,
instr(testvar.codes, '|',1,s.num) p1,
instr(testvar.codes||'|', '|',1,s.num + 1)- instr(testvar.codes, '|',1,s.num) - 1 p2
from testvar, (select level num from dual connect by level <= 15) s
where s.num <= (length(testvar.codes)-length(replace(testvar.codes, '|')))
) t;
I hope you can adapt it for mysql.