gpt4 book ai didi

mysql - 是否可以创建此 mysql 函数?

转载 作者:行者123 更新时间:2023-11-29 01:20:56 26 4
gpt4 key购买 nike

我是 mysql 编程的新手,我会创建一个带有字符串参数的 mysql 函数 myFunction;此函数查询 myTable 并从查询结果中返回一个字符串,如下例所示:

myTable
---------------
|id | value |
---------------
| id1 |value1 |
| id2 |value2 |
| id3 |value3 |
| id4 |value4 |
---------------

调用这个函数是这样的

myFunction('value2#value1#value4')

必须返回

'id2#id1#id4'

非常感谢

最佳答案

这是一个关于如何做到这一点的演示,当然你可以将所有内容放在一起,但我发现拆分功能更清晰。

检查 SQL Fiddle

我的 table

-- the table def
create table myTable (id char(3), value char(6));
insert into myTable values( 'id1', 'value1');
insert into myTable values( 'id2', 'value2');
insert into myTable values( 'id3', 'value3');
insert into myTable values( 'id4', 'value4');

获取特定的id

-- get Id by Value
CREATE function getIdByValue( theValue TEXT )
RETURNS TEXT READS SQL DATA
BEGIN
DECLARE theId TEXT;
DECLARE ok INT DEFAULT FALSE;
DECLARE crs CURSOR FOR
SELECT id FROM myTable where value = theValue;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET ok = TRUE;

SET theId = '';

OPEN crs;
read_loop: LOOP
FETCH crs INTO theId;
IF ok THEN
LEAVE read_loop;
END IF;
END LOOP;
CLOSE crs;
RETURN theId;
END//

您描述的 MyFunction

-- the myFunction, usage: myFunction('value2#value1#value4')
CREATE function myFunction( v TEXT )
RETURNS TEXT READS SQL DATA
BEGIN
DECLARE theId TEXT;
DECLARE theIds TEXT;
DECLARE theValue TEXT;
DECLARE vInstr INT;

SET theId = '';
SET theIds = '';

v_loop: LOOP

SET vInstr = INSTR(v,'#');
IF vInstr = 0 THEN
SET theValue = v;
SET theId = getIdByValue(theValue);
ELSE
SET theValue = SUBSTRING(v, 1, vInstr-1);
SET v = SUBSTRING(v, vInstr+1);
SET theId = concat( getIdByValue(theValue), '#');
END IF;

SET theIds = CONCAT(theIds, theId);

IF vInstr = 0 THEN
LEAVE v_loop;
END IF;

END LOOP;

RETURN theIds;
END//

电话

SELECT myFunction( 'value2' );
SELECT myFunction( 'value2#value4' );
SELECT myFunction( 'value2#value4#value1' );
SELECT myFunction( 'value2#value4#value1#value3' );

结果

id2
id2#id4
id2#id4#id1
id2#id4#id1#id3

关于mysql - 是否可以创建此 mysql 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30133911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com