Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi,
i want to insert comma separated values into datatable table
for example
the comma saperated string like '123,char,456,vargh'
has to be inserted into table like using storeprocedure
col1 col2,col3 col4
123  char  456  vargh
inserting into a single column i know but i need above process

thanks in advance
Posted
Updated 8-Jan-12 23:24pm
v4

Hi,
try this one
SELECT col1 + ',' + col2 + ',' + col3 + ',' + col4 From tableName
 
Share this answer
 
Hello Friend...

For your solution you need to follow this steps...

1) First Create one Function in your database like this...
SQL
ALTER FUNCTION DBO.SPLIT(@STRING VARCHAR(8000), @DELIMITER CHAR(1))       
    RETURNS @TEMPTABLE TABLE (ID INT IDENTITY(1,1),ITEMS VARCHAR(8000))       
    AS       
    BEGIN       
        DECLARE @IDX INT       
        DECLARE @SLICE VARCHAR(8000)       
          
        SELECT @IDX = 1       
            IF LEN(@STRING)<1 OR @STRING IS NULL  RETURN       
          
        WHILE @IDX!= 0       
        BEGIN       
            SET @IDX = CHARINDEX(@DELIMITER,@STRING)       
            IF @IDX!=0       
                SET @SLICE = LEFT(@STRING,@IDX - 1)       
            ELSE       
                SET @SLICE = @STRING       
              
            IF(LEN(@SLICE)>0)  
                INSERT INTO @TEMPTABLE(ITEMS) VALUES(@SLICE)       
      
            SET @STRING = RIGHT(@STRING,LEN(@STRING) - @IDX)       
            IF LEN(@STRING) = 0 BREAK       
        END   
    RETURN       
    END 


2) Now you need to call insert query like this....

SQL
INSERT INTO TABLENAME 
SELECT * FROM (
	SELECT TOP(4) id,items FROM	dbo.split('123,char,456,vargh',',')
) up
PIVOT (MAX(ITEMS) FOR ID IN ([1],[2],[3],[4])) as pvt
GO
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900