數據
A
B
C
這在系統自己種並不包含,需要自定義函數,先看看MSSQL的自定義函數:
CREATE function StrSplit(@c varchar(2000),@split varchar(2)=',')
returns @t table(col varchar(100))
as
begin
while(charindex(@split,@c)<>0)
begin
insert @t(col) values (substring(@c,1,charindex(@split,@c)-1))
set @c = stuff(@c,1,charindex(@split,@c),'')
end
insert @t(col) values (@c)
return
end
GO
使用的時候
select * from dbo.StrSplit('52,50,55',','))
即可。
在MySQL裡面,我也希望能用自定義函數,但是,目前的版本並不支持返回table這種類型的函數,所以不得不考慮使用存儲過程。
首先,了解MySQL創建臨時表的語句:
set global log_bin_trust_function_creators = 1;
DELIMITER $$
DROP FUNCTION IF EXISTS `Myf`$$
CREATE DEFINER=`root`@`%` FUNCTION `Myf`() RETURNS varchar(50) CHARSET utf8
begin
return concat('-FUNCTION');
end$$
DELIMITER ;
然後看看使用:
SELECT Myf('MYF?');
然後是存儲過程:
DELIMITER //
DROP PROCEDURE IF EXISTS split_string //
CREATE PROCEDURE split_string (
IN input VARCHAR(2000)
, IN `delimiter` VARCHAR(10)
)
SQL SECURITY INVOKER
COMMENT
'Splits a supplIEd string using using the given delimiter,
placing values in a temporary table'
BEGIN
DECLARE cur_position INT DEFAULT 1 ;
DECLARE remainder VARCHAR(2000);
DECLARE cur_string VARCHAR(1000);
DECLARE delimiter_length TINYINT UNSIGNED;
DROP TEMPORARY TABLE IF EXISTS SplitValues;
CREATE TEMPORARY TABLE SplitValues (
value VARCHAR(1000) NOT NULL PRIMARY KEY
) ENGINE=MyISAM;
SET remainder = input;
SET delimiter_length = CHAR_LENGTH(delimiter);
WHILE CHAR_LENGTH(remainder) > 0 AND cur_position > 0 DO
SET cur_position = INSTR(remainder, `delimiter`);
IF cur_position = 0 THEN
SET cur_string = remainder;
ELSE
SET cur_string = LEFT(remainder, cur_position - 1);
END IF;
IF TRIM(cur_string) != '' THEN
INSERT INTO SplitValues VALUES (cur_string);
END IF;
SET remainder = SUBSTRING(remainder, cur_position + delimiter_length);
END WHILE;
END //
DELIMITER ;
/*
Tests
*/
CALL split_string('Steve,Jan,Bobby,Jay,Kaj,Colin',',');
SELECT * FROM SplitValues;
CREATE TEMPORARY TABLE TestJoin (join_fIEld VARCHAR(20) PRIMARY KEY) ENGINE=MEMORY;
INSERT INTO TestJoin VALUES ('Kaj'),('Colin');
SELECT tj.* FROM TestJoin tj
INNER JOIN SplitValues sv
ON tj.join_fIEld = sv.value;
//這個代碼來自MySQL官方,我沒有驗證