How can i concat the values in MySql? - mysql

Please find the below code, The below code is sql server code[Stored Procedure] i am converting sql to mysql in this link mysql and below is the sql SP
USE databasename
GO
ALTER PROCEDURE GetSbsberIDbyDept
#P_DepartmentIds varchar(max),
#OP_ID varchar(max) output
AS
BEGIN
Declare #Position int
Declare #length int
Declare #value varchar(8000)
Declare #SubscribrIDs varchar(max)
Declare #FinalSubscriberids varchar(max) = ''
SET #Position = 0
SET #length = 0
select #P_DepartmentIds
WHILE CHARINDEX(',', #P_DepartmentIds, #Position+1)>0
BEGIN
set #Length = CHARINDEX(',', #P_DepartmentIds, #Position+1) - #Position
set #value = SUBSTRING(#P_DepartmentIds, #Position, #length)
select #SubscribrIDs = STUFF((SELECT ', ' + cast(SubscriberId as varchar(max)) from SbsberDetails
where Deptid = #value and ParentId is null order by SubscriberId asc FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,2,'')
if(#SubscribrIDs is not null)
begin
set #FinalSubscriberids += cast(#SubscribrIDs as varchar(max)) + ',';
end
set #Position = CHARINDEX(',', #P_DepartmentIds, #Position + #length) +1
END
SET #OP_ID = #FinalSubscriberids
END
And i converted to MySql but i am getting the error in STUFF statement like STUFF is not valid input at this position, below is the Mysql code
USE databasename
DELIMITER //
CREATE PROCEDURE GetSbsberIDbyDept(
p_P_DepartmentIds longtext,
p_OP_ID out longtext )
BEGIN
Declare v_Position int;
Declare v_length int;
Declare v_value varchar(8000);
Declare v_SubscribrIDs longtext;
Declare v_FinalSubscriberids longtext Default '';
SET v_Position = 0;
SET v_length = 0;
select p_P_DepartmentIds
WHILE; CHARINDEX(',', p_P_DepartmentIds, v_Position+1)>0
BEGIN
set v_length = CHARINDEX(',', p_P_DepartmentIds, v_Position+1) - v_Position;
set v_value = SUBSTRING(p_P_DepartmentIds, v_Position, v_length);
set v_SubscribrIDs = STUFF((SELECT Concat(', ' , cast(SubscriberId as longtext)) from SbsberDetails
where Deptid = v_value and ParentId is null order by SubscriberId asc FOR XML; PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,2,'')
if(v_SubscribrIDs is not null)
then
set v_FinalSubscriberids += concat(cast(v_SubscribrIDs as longtext) , ',');
end if;
set v_Position = CHARINDEX(',', p_P_DepartmentIds, v_Position + v_length) +1;
END;
SET p_OP_ID = v_FinalSubscriberids;
END;
//
DELIMITER ;
How do i convert the above sql code to MySql?

STUFF is SQL server function so it's thrown error in mysql, The thing that i got your are trying to row concat but in mysql there is funtion name GROUP_CONCAT for group cancating ,so you can use it instead of stuff

Related

How to remove Vietnamese Character in MySQL

My Code MYSQL
DELIMITER //
CREATE FUNCTION fNonUnicode(p_inputVar LONGTEXT )
RETURNS LONGTEXT
BEGIN
IF (p_inputVar IS NULL OR p_inputVar = '') THEN RETURN '';
END IF;
DECLARE v_RT LONGTEXT;
DECLARE v_SIGN_CHARS NVARCHAR(256);
DECLARE v_UNSIGN_CHARS NVARCHAR (256);
SET v_SIGN_CHARS = Concat(N'ăâđêôơưàảãạáằẳẵặắầẩẫậấèẻẽẹéềểễệếìỉĩịíòỏõọóồổỗộốờởỡợớùủũụúừửữựứỳỷỹỵýĂÂĐÊÔƠƯÀẢÃẠÁẰẲẴẶẮẦẨẪẬẤÈẺẼẸÉỀỂỄỆẾÌỈĨỊÍÒỎÕỌÓỒỔỖỘỐỜỞỠỢỚÙỦŨỤÚỪỬỮỰỨỲỶỸỴÝ' , NCHAR(272) + NCHAR(208));
SET v_UNSIGN_CHARS = N'aadeoouaaaaaaaaaaaaaaaeeeeeeeeeeiiiiiooooooooooooooouuuuuuuuuuyyyyyAADEOOUAAAAAAAAAAAAAAAEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOUUUUUUUUUUYYYYYDD';
DECLARE v_COUNTER int;
DECLARE v_COUNTER1 int;
SET v_COUNTER = 1;
WHILE (v_COUNTER <= CHAR_LENGTH(RTRIM(p_inputVar)))
DO
SET v_COUNTER1 = 1;
WHILE (v_COUNTER1 <= CHAR_LENGTH(RTRIM(v_SIGN_CHARS)) + 1)
DO
IF UNICODE(SUBSTRING(v_SIGN_CHARS, v_COUNTER1,1)) = UNICODE(SUBSTRING(p_inputVar,v_COUNTER ,1))
THEN
IF v_COUNTER = 1 THEN
SET p_inputVar = CONCAT(SUBSTRING(v_UNSIGN_CHARS, v_COUNTER1,1) , SUBSTRING(p_inputVar, v_COUNTER+1,CHAR_LENGTH(RTRIM(p_inputVar))-1));
ELSE
SET p_inputVar = CONCAT(SUBSTRING(p_inputVar, 1, v_COUNTER-1) ,SUBSTRING(v_UNSIGN_CHARS, v_COUNTER1,1) , SUBSTRING(p_inputVar, v_COUNTER+1,CHAR_LENGTH(RTRIM(p_inputVar))- v_COUNTER));
END IF;
BREAK
END IF;
SET v_COUNTER1 = v_COUNTER1 +1;
END WHILE;
SET v_COUNTER = v_COUNTER +1;
END WHILE;
-- SET #inputVar = replace(#inputVar,' ','-')
RETURN p_inputVar;
END;
//
DELIMITER ;
But Error:You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'DECLARE v_RT LONGTEXT;
Finnaly: I want to use:fNonUnicode("Xin chào các bạn") return Xin chao cac ban
MySQL Function to remove accents and special characters
DROP FUNCTION IF EXISTS fn_remove_accents;
DELIMITER |
CREATE FUNCTION fn_remove_accents( textvalue VARCHAR(10000) ) RETURNS VARCHAR(10000)
BEGIN
SET #textvalue = textvalue;
-- ACCENTS
SET #withaccents = 'ŠšŽžÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝŸÞàáâãäåæçèéêëìíîïñòóôõöøùúûüýÿþƒ';
SET #withoutaccents = 'SsZzAAAAAAACEEEEIIIINOOOOOOUUUUYYBaaaaaaaceeeeiiiinoooooouuuuyybf';
SET #count = LENGTH(#withaccents);
WHILE #count > 0 DO
SET #textvalue = REPLACE(#textvalue, SUBSTRING(#withaccents, #count, 1), SUBSTRING(#withoutaccents, #count, 1));
SET #count = #count - 1;
END WHILE;
-- SPECIAL CHARS
SET #special = '!##$%¨&*()_+=§¹²³£¢¬"`´{[^~}]<,>.:;?/°ºª+*|\\''';
SET #count = LENGTH(#special);
WHILE #count > 0 do
SET #textvalue = REPLACE(#textvalue, SUBSTRING(#special, #count, 1), '');
SET #count = #count - 1;
END WHILE;
RETURN #textvalue;
END
|
DELIMITER ;
please try with code below
DROP FUNCTION IF EXISTS fn_remove_accents;
DELIMITER //
CREATE FUNCTION fn_remove_accents(textvalue TEXT)
RETURNS TEXT
BEGIN
SET #textvalue = textvalue;
-- ACCENTS
SET #withaccents = 'ăâđêôơưàảãạáằẳẵặắầẩẫậấèẻẽẹéềểễệếìỉĩịíòỏõọóồổỗộốờởỡợớùủũụúừửữựứỳỷỹỵýĂÂĐÊÔƠƯÀẢÃẠÁẰẲẴẶẮẦẨẪẬẤÈẺẼẸÉỀỂỄỆẾÌỈĨỊÍÒỎÕỌÓỒỔỖỘỐỜỞỠỢỚÙỦŨỤÚỪỬỮỰỨỲỶỸỴÝ';
SET #withoutaccents = 'aadeoouaaaaaaaaaaaaaaaeeeeeeeeeeiiiiiooooooooooooooouuuuuuuuuuyyyyyAADEOOUAAAAAAAAAAAAAAAEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOUUUUUUUUUUYYYYY';
SET #count = LENGTH(#withaccents);
WHILE #count > 0 DO
SET #textvalue = REPLACE(#textvalue, SUBSTRING(#withaccents, #count, 1), SUBSTRING(#withoutaccents, #count, 1));
SET #count = #count - 1;
END WHILE;
RETURN #textvalue;
END
//
DELIMITER ;

How do I convert this MSSQL cursor function into MYSQL

I am trying to convert a MSSQL function into MySQL. Here is what I've done so far. Can someone please take a look at it ?
ALTER FUNCTION [dbo].[GetCommaDelimitedCategoryIDs]
(
#datafeedcategoryinfoid int
)
RETURNS varchar(2000)
AS
BEGIN
DECLARE #category_list varchar(4500), #categoryid varchar(20)
SET #category_list = ''
DECLARE category_cursor CURSOR
LOCAL FAST_FORWARD FOR
SELECT DISTINCT categoryid
FROM category_mapping
WHERE datafeedcategoryinfoid = #datafeedcategoryinfoid
OPEN category_cursor;
FETCH NEXT FROM category_cursor
INTO #categoryid;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #category_list = #category_list + #categoryid + ','
FETCH NEXT FROM category_cursor
INTO #categoryid;
END
CLOSE category_cursor;
DEALLOCATE category_cursor;
IF (LEN(#category_list) > 0)
SET #category_list = SUBSTRING(#category_list, 1, LEN(#category_list) - 1)
RETURN #category_list
END
And here is the MySQL function
DELIMITER $$
CREATE DEFINER=``#`` FUNCTION `GetCommaDelimitedCategoryIDs`(
p_datafeedcategoryinfoid int
) RETURNS varchar(2000) CHARSET latin1
BEGIN
DECLARE v_category_list varchar(4500);
DECLARE v_categoryid varchar(20);
DECLARE category_cursor CURSOR FOR
SELECT DISTINCT categoryid
FROM category_mapping
WHERE datafeedcategoryinfoid = p_datafeedcategoryinfoid;
SET v_category_list = '';
OPEN category_cursor;
myloop: LOOP
FETCH category_cursor INTO v_categoryid;
IF done THEN
LEAVE myloop;
END IF;
SET v_category_list = Concat(v_category_list , v_categoryid , ',');
FETCH category_cursor INTO v_categoryid;
END LOOP;
CLOSE category_cursor;
IF (CHAR_LENGTH(RTRIM(v_category_list)) > 0) THEN
SET v_category_list = SUBSTRING(v_category_list, 1, CHAR_LENGTH(RTRIM(v_category_list)) - 1);
END IF;
RETURN v_category_list;
END
But the above function doesn't return the value. Mysql Workbench doesn't return any error, how do i debug ?
Isn't this a job for group_concat()? Something like:
select group_concat(distinct categoryid order by categoryid SEPARATOR ',')
from category_mapping
where datafeedcategoryinfoid = p_datafeedcategoryinfoid;
Here is a demo of group_concat().

Create function for an update

I used a column 'Title' in a table 'incident'. This column contains some information .Among this information, three character that indicates the region .these three character are usually found after ('on', ':'). I want to execute a function (mysql) which allows: 1) if the three character taken from the 'Title' column, which are located after 'on', are( kef or bej or jen) so the result will be stored in a column 'test' in the same table. 2) if the first is not achieved then takes the three character which are located after ':' and stored in a column 'test1' in the same table.
there is the code that i used :
delimiter |
CREATE FUNCTION METTER5 (s VARCHAR(2000)) RETURNS VARCHAR(10000)
DETERMINISTIC
BEGIN
DECLARE open INT;
DECLARE close INT;
DECLARE someLimit INT;
DECLARE str VARCHAR(2000);
DECLARE str1 VARCHAR(2000);
DECLARE str2 VARCHAR(2000);
DECLARE str3 VARCHAR(2000);
DECLARE toFind VARCHAR(2000);
DECLARE co VARCHAR(2000);
SET co='';
SET open = 1;
SET close = 1;
SET toFind = s ;
SET someLimit =100;
SET str='';
SET str1='';
SET str2='';
/* SET tofind=concat(tofind,'sur','');*/
SET str =substring(trim(substring_index(s,'sur',-1)),1,3);
SET str1 =substring(trim(substring_index(s,'du',-1)),1,3);
SET str2 =substring(trim(substring_index(s,':',-1)),1,3);
IF (str in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB')) =1 THEN set co = str ;
ELSE IF ((str not in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB')) and (str1 in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB')))=1 THEN set co = str1 ;
ELSE IF ((str1 not in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB'))and (str2 in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB')))=1 THEN SET co = str2 ;
ELSE set co = '1' ;
END IF;
END IF;
END IF;
return co;
END |
delimiter;
and there is the query that i used :
update incident set test =METTER5 (Title) WHERE Affected_CI like 'other ci' and open_time between '2015-01-01' and '2015-01-30'
but after the running , there is the problem : Unknown column 'description' in 'field list'
thanks.

MySql Procedure for randomly populating rows only populates one row

I have a procedure that populates randomly records in a table.
But when i execute that procedure, the procedure inserts only one row.
CAN ANYONE HELP!
create procedure aa
( #row INT
)
as
begin
declare #numint as int
declare #string as VARCHAR(10)
declare #length as INT
declare #code as INT
declare #oid as uniqueidentifier
set #numint =0;
WHILE #numint <= #row
BEGIN
SET #numint = #numint + 1;
set #oid = newid();
SET #length = ROUND(10*RAND(),0);
SET #string = '';
WHILE #length > 0 BEGIN
SET #length = #length-1;
SET #code = ROUND(10*RAND(),0) - 1;
IF #code BETWEEN 1 AND 26
SET #string = #string + CHAR(ASCII('a')+#code-1);
ELSE
SET #string = #string + ' ';
END
end
-- Ready for the record
SET NOCOUNT ON;
INSERT INTO test_table VALUES (
#oid,
#numint,
ROUND(2000000*RAND()-1000000,2),
CONVERT(DATETIME, ROUND(50000*RAND()-10000,2)),
#string
)
END
exec procedure '10'
Your insert statement is outside of the loop. Move it up to be inside the first loop and you should get the correct number of rows.

Issue in adding two outputs from MySQL function inside another function

CREATE DEFINER=`root`#`localhost` FUNCTION `F_GetProjectCostPerEmployeeInProject`(id VARCHAR(20)) RETURNS DECIMAL(30,2)
BEGIN
DECLARE e_id VARCHAR(20);
DECLARE finished INT ;
DECLARE temp DECIMAL(30,2);
DECLARE temp2 DECIMAL(30,2);
DECLARE TotalCostOfEmployees DECIMAL(30,2);
DECLARE cur CURSOR FOR SELECT DISTINCT e_id FROM project_employee WHERE project_id=id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
emploop : LOOP
FETCH cur INTO e_id;
IF finished =1 ;
LEAVE emploop;
END IF ;
SET TotalCostOfEmployees = TotalCostOfEmployees + ( F_TotalManDaysPerEmployee(e_id,id)*(F_GetEmployeeGradeSal(e_id));
END LOOP emploop;
RETURN TotalCostOfEmployees;
END$$
The problem is its giving error at line :
SET TotalCostOfEmployees = TotalCostOfEmployees + ( F_TotalManDaysPerEmployee(e_id,id)*(F_GetEmployeeGradeSal(e_id));
This is the error :
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 '; leave emploop; end if ;
set TotalCostOfEmployees = TotalCostOfEmploy' at line 12
Use the SELECT ... INTO clause
SELECT TotalCostOfEmployees + ( F_TotalManDaysPerEmployee(e_id,id)*(F_GetEmployeeGradeSal(e_id))
INTO TotalCostOfEmployees;
Why are you using a cursor for this at all?
SELECT SUM(F_TotalManDaysPerEmployee(e_id, id) * F_GetEmployeeGradeSal(e_id)) AS TotalCostOfEmployees
FROM (
SELECT DISTINCT e_id
FROM project_employee
WHERE project_id = id
) q
I solved it via this way:
enter code BEGIN DECLARE e_id VARCHAR(20);
DECLARE finished INT ;
DECLARE salary DECIMAL(30,2);
DECLARE TotalCostOfEmployees DECIMAL(30,2) ;
DECLARE cur CURSOR FOR SELECT DISTINCT Emp_code FROM project_employee WHERE project_id=p_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
SET finished = 0;
OPEN cur;
SET TotalCostOfEmployees =0.0;
emploop : LOOP
FETCH cur INTO e_id;
IF finished = 1 THEN
LEAVE emploop;
END IF ;
SELECT COALESCE( (F_TotalManDaysPerEmployee(e_id,p_id)* F_GetEmployeeGradeSal(e_id))/22,0.0)
INTO salary;
SET TotalCostOfEmployees = TotalCostOfEmployees + salary;
/*SELECT (TotalCostOfEmployees + ifnull(salary,0.0)) into TotalCostOfEmployees; */
END LOOP emploop;
CLOSE cur;
RETURN TotalCostOfEmployees;
END$$