2015-03-25 68 views
-1

我要轉換的以下功能可按建立在MySQL轉換SQL函數到mysql

CREATE FUNCTION dbo.DistinctList 
(
    @List VARCHAR(MAX), 
    @Delim CHAR 
) 
RETURNS 
VARCHAR(MAX) 
AS 
BEGIN 
    DECLARE @ParsedList TABLE 
    (
     Item VARCHAR(MAX) 
    ) 

    DECLARE @list1 VARCHAR(MAX), @Pos INT, @rList VARCHAR(MAX) 

    SET @list = LTRIM(RTRIM(@list)) + @Delim 
    SET @pos = CHARINDEX(@delim, @list, 1) 

    WHILE @pos > 0 
    BEGIN 
     SET @list1 = LTRIM(RTRIM(LEFT(@list, @pos - 1))) 

     IF @list1 <> '' 
      INSERT INTO @ParsedList VALUES (CAST(@list1 AS VARCHAR(MAX))) 

     SET @list = SUBSTRING(@list, @pos+1, LEN(@list)) 
     SET @pos = CHARINDEX(@delim, @list, 1) 
    END 

     SELECT @rlist = COALESCE(@rlist+',','') + item 
     FROM (SELECT DISTINCT Item FROM @ParsedList) t 

     RETURN @rlist 
END 

工作,我發現這個功能在http://blog.sqlauthority.com/2009/01/15/sql-server-remove-duplicate-entry-from-comma-delimited-string-udf/

+0

請勿將內容存儲在以逗號分隔的列表中。改用結合表。這樣,你可以使用常規的SQL來做你想做的,而不是從網上下載神祕的功能。 – 2015-03-25 10:40:22

回答

0

我不知道爲什麼人們分級下來我的問題。 無論如何,我能夠拿出答案。

Delimiter // 
CREATE FUNCTION DistinctList 
(
List TEXT, 
Delim CHAR 
) 
RETURNS 
TEXT 

BEGIN 
DECLARE list1 TEXT; 
DECLARE Pos INT; 
DECLARE rList TEXT; 
DROP TEMPORARY TABLE IF EXISTS ParsedList; 
Create temporary table if not exists ParsedList 
(
Item VARCHAR(60) 
) ENGINE=MEMORY; 


SET list = CONCAT(list, Delim); 
SET pos = length(SUBSTRING_INDEX(list, delim, 1)); 
WHILE (pos > 0) DO 
SET list1 = SUBSTRING(list, 1, pos); 
IF list1 <> '' THEN 
    INSERT INTO ParsedList VALUES (list1); 
END IF; 
SET list = SUBSTRING(list, pos+2); 
SET pos = length(SUBSTRING_INDEX(list, delim, 1)); 
END WHILE; 

SELECT GROUP_CONCAT(DISTINCT Item) FROM ParsedList INTO rlist; 
RETURN rlist; 
END// 
Delimiter ;