逗号分隔列表到字符串 sql
Comma delimited list to string sql
我需要从变量转换以下值:
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
试试这个:
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');
DECLARE @VAL AS VARCHAR(MAX)
SELECT @VAL = '1234,1234,12345,12346,1344,4564'
SELECT '''' + REPLACE(@VAL,',',''',''') + ''''
使用 REPLACE()
和 CONCAT()
:
select concat("\'", replace('1234,1234,12345,12346,1344,4564', ',', "\',\'"), "\'")
我需要从变量转换以下值:
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
试试这个:
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');
DECLARE @VAL AS VARCHAR(MAX)
SELECT @VAL = '1234,1234,12345,12346,1344,4564'
SELECT '''' + REPLACE(@VAL,',',''',''') + ''''
使用 REPLACE()
和 CONCAT()
:
select concat("\'", replace('1234,1234,12345,12346,1344,4564', ',', "\',\'"), "\'")