1

i need to convert the following values from a variable:

1234,1234,12345,12346,1344,4564

to this:

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

using an SQL function.

I have tried:

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

But i get:

1234,1234,12345,12346,1344,4564
3
  • select '''' + replace(@yourvariable,',',''',''') + '''' Commented Jan 15, 2015 at 12:29
  • COALESCE returns the first non-null value from its arguments. It's not related to string manipulation. Additionally, DON'T use varchar(max), it's intended for use as a BLOB, not as a convenient string without size Commented Jan 15, 2015 at 12:30
  • Ugh, why? Are you then going to put @listStr into something like WHERE column IN (' + @listStr + ')? You really should look into table-valued parameters or, if you are on < 2008, splitting strings. Commented Jan 15, 2015 at 15:07

3 Answers 3

2

Try this:

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

Check this SQL FIDDLE DEMO

OUTPUT

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

EDIT

Use User defined function:

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');
Sign up to request clarification or add additional context in comments.

1 Comment

whats UDF? Scalar_Function
1
DECLARE @VAL AS VARCHAR(MAX)
SELECT @VAL = '1234,1234,12345,12346,1344,4564'
SELECT '''' + REPLACE(@VAL,',',''',''') + ''''

Comments

0

Using REPLACE() and CONCAT():

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.