逗号分隔列表到字符串sql

时间:2015-01-15 12:25:22

标签: sql sql-server tsql replace string-concatenation

我需要从变量中转换以下值:

1234,1234,12345,12346,1344,4564

到此:

'1234','1234','12345','12346','1344','4564'

使用SQL函数。

我试过了:

DECLARE @VAL AS VARCHAR(MAX)
SELECT @VAL = '1234,1234,12345,12346,1344,4564'

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' ,'') + @VAL
SELECT @listStr AS 'List'
GO

但我明白了:

1234,1234,12345,12346,1344,4564

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT '''' + REPLACE('1234,1234,12345,12346,1344,4564', ',', ''',''') + '''';

选中 SQL FIDDLE DEMO

<强>输出

|                                    COLUMN_0 |
|---------------------------------------------|
| '1234','1234','12345','12346','1344','4564' |

修改

使用用户定义的功能:

CREATE FUNCTION dbo.ufnReplace(@Val VARCHAR(MAX))
RETURNS VARCHAR(MAX) 
AS 
BEGIN
    SELECT @Val = '''' + REPLACE(@Val, ',', ''',''') + '''';
    RETURN @Val;
END;

SELECT dbo.ufnReplace('1234,1234,12345,12346,1344,4564');

答案 1 :(得分:1)

DECLARE @VAL AS VARCHAR(MAX)
SELECT @VAL = '1234,1234,12345,12346,1344,4564'
SELECT '''' + REPLACE(@VAL,',',''',''') + ''''

答案 2 :(得分:0)

使用REPLACE()CONCAT()

select concat("\'", replace('1234,1234,12345,12346,1344,4564', ',', "\',\'"), "\'")