如何将SQL查询转换为MYSQL查询?

时间:2015-02-19 16:00:58

标签: mysql tsql

我在tsql中开发了一个用于拆分字符串的函数,但是mysql没有一些内置函数。我需要在MYSQL中运行,因为我是mysql的新手。功能应该接受2个参数   1.要拆分的字符串  2.分隔符(','或其他) 请回复我。

3 个答案:

答案 0 :(得分:0)

在mysql中,他们不支持像sqlserver这样的功能。所以在mysql中拆分很困难

SELECT e.`studentId`, SPLIT(",", c.`courseNames`)[e.`courseId`]

FROM ..

SELECT TRIM(SUBSTRING_INDEX(yourcolumn,',',1)), TRIM(SUBSTRING_INDEX(yourcolumn,',',-1)) FROM yourtable

答案 1 :(得分:0)

CREATE FUNCTION [dbo].[SplitString] 
(
    @RowData nvarchar(2000),
    @SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(
    --Id int identity(1,1),
    Data nvarchar(100)
) 
AS  
BEGIN 
    Declare @Cnt int
    Set @Cnt = 1

    While (Charindex(@SplitOn,@RowData)>0)
    Begin
        Insert Into @RtnValue (data)
        Select 
            Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1
    End

    Insert Into @RtnValue (data)
    Select Data = ltrim(rtrim(@RowData))

    Return
END

答案 2 :(得分:0)

我已经在互联网上找到了解决方案。

DELIMITER //
DROP FUNCTION IF EXISTS `splitAndTranslate` //
CREATE FUNCTION splitAndTranslate(str TEXT, delim VARCHAR(124))
RETURNS TEXT
DETERMINISTIC
BEGIN
    DECLARE i INT DEFAULT 0;    -- total number of delimiters
    DECLARE ctr INT DEFAULT 0;  -- counter for the loop
    DECLARE str_len INT;        -- string length,self explanatory
    DECLARE out_str text DEFAULT '';    -- return string holder
    DECLARE temp_str text DEFAULT '';   -- temporary string holder
    DECLARE temp_val VARCHAR(255) DEFAULT '';   -- temporary string holder for query

    -- get length
    SET str_len=LENGTH(str);    

    SET i = (LENGTH(str)-LENGTH(REPLACE(str, delim, '')))/LENGTH(delim) + 1;    
        -- get total number delimeters and add 1
        -- add 1 since total separated values are 1 more than the number of delimiters

    -- start of while loop
    WHILE(ctr<i) DO
        -- add 1 to the counter, which will also be used to get the value of the string
        SET ctr=ctr+1; 

        -- get value separated by delimiter using ctr as the index
        SET temp_str = REPLACE(SUBSTRING(SUBSTRING_INDEX(str, delim, ctr), LENGTH(SUBSTRING_INDEX(str, delim,ctr - 1)) + 1), delim, '');

        -- query real value and insert into temporary value holder, temp_str contains the exploded ID           
        SELECT <real_value_column> INTO temp_val FROM <my_table> WHERE <table_id>=temp_str;

        -- concat real value into output string separated by delimiter
            SET out_str=CONCAT(out_str, temp_val, ',');
    END WHILE;
    -- end of while loop

    -- trim delimiter from end of string
    SET out_str=TRIM(TRAILING delim FROM out_str);
    RETURN(out_str);    -- return 

END//

参考http://www.slickdev.com/2008/09/15/mysql-query-real-values-from-delimiter-separated-string-ids/