0

i have

id | dvr
1  | 1,2,3
2  | 1,3,4
3  | 1,5,6,7,8

and would like to have

id | dvr
1  | 1
1  | 2
1  | 3
2  | 1
2  | 3
2  | 4
... and so on

what is the fastest query i should use?

3
  • 4
    What's your DBMS? Anyway there are tons of answers about this. Commented Jan 28, 2015 at 9:31
  • 3
    It very much depends on what database you are using. Please update your question with this vital information. Commented Jan 28, 2015 at 9:32
  • 1
    Another thing, which we greatly value before answering any questions is to show us what was your attempt at writing a query and find a solution yourself. Commented Jan 28, 2015 at 9:35

2 Answers 2

1

Make a sql function as below:

create Function [dbo].[fun_CSVToTable] 
(
    @LIST varchar(7000),
    @Delimeter varchar(10)
)
RETURNS @RET1 TABLE (RESULT BIGINT)
AS
BEGIN
    DECLARE @RET TABLE(RESULT BIGINT)

    IF LTRIM(RTRIM(@LIST))='' RETURN  

    DECLARE @START BIGINT
    DECLARE @LASTSTART BIGINT
    SET @LASTSTART=0
    SET @START=CHARINDEX(@Delimeter,@LIST,0)

    IF @START=0
    INSERT INTO @RET VALUES(SUBSTRING(@LIST,0,LEN(@LIST)+1))

    WHILE(@START >0)
    BEGIN
        INSERT INTO @RET VALUES(SUBSTRING(@LIST,@LASTSTART,@START-@LASTSTART))
        SET @LASTSTART=@START+1
        SET @START=CHARINDEX(@Delimeter,@LIST,@START+1)
        IF(@START=0)
        INSERT INTO @RET VALUES(SUBSTRING(@LIST,@LASTSTART,LEN(@LIST)+1))
    END

    INSERT INTO @RET1 SELECT * FROM @RET
    RETURN 
END
Sign up to request clarification or add additional context in comments.

Comments

0

If you are running postgresql and dvr column is text you could do:

select
  id,
  unnest(string_to_array(dvr,','))
from your_table;

1 Comment

i'm using MS sql server

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.