0

What mistake I am making in this sql query

    Declare @str Varchar(100) = 'asasa,bsasas,csasa,dsczxvvc'
    declare @d varchar(2)=','

SELECT 
     RIGHT(LEFT(@str,Number-1), 
    CHARINDEX(@d,REVERSE(LEFT(@d+@str,Number-1)))) 
FROM 
    master..spt_values
WHERE 
    Type = 'P' AND Number BETWEEN 1 AND  LEN(@str)
    AND SUBSTRING(@str,Number,1) = @d

Expected Result

(No column name)
asasa
bsasas
csasa
dsczxvvc

Actual Result

(No column name)
asasa
bsasas
csasa

3 Answers 3

3

Your AND SUBSTRING(@str, Number, 1) = @d is forcing a comma to be at the end of dsczxvvc...there isn't one. asasa,bsasas,csasa,dsczxvvc, works.

Sign up to request clarification or add additional context in comments.

Comments

1

add one more comma at the end of string

you can directly add comma in the string like = "asasa,bsasas,csasa,dsczxvvc,"

or

handle this thing in sql side.

Declare @str Varchar(100) set @str = 'asasa,bsasas,csasa,dsczxvvc' declare @d varchar(2) set @d =','

set @str = @str + ','

SELECT RIGHT(LEFT(@str,Number-1), CHARINDEX(@d,REVERSE(LEFT(@d+@str,Number-1)))) FROM master..spt_values WHERE Type = 'P' AND Number BETWEEN 1 AND LEN(@str) AND SUBSTRING(@str,Number,1) = @d

Comments

1

This is because since the last string portion does not have the seperator at the end of the string If you add the following code just before the SELECT statement, it will work

set @str = @str + @d

There are many split functions on the web, you can use one of them actually.

Split string using CLR function

Split using XML

SQL Server split string function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.