Click here to Skip to main content
Click here to Skip to main content

HTML Table to SQL table conversion

By , 2 Jan 2013
 

Introduction

HTML Table to SQL table conversion - An example.

Using the code  

First parse value by <TR> tag and then by <TD>.

Here it is an example or a trick... 

Create this function that will used for parse values  

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[ParseValues]
(@String varchar(8000), @Delimiter varchar(max) )
RETURNS @RESULTS TABLE (ID int identity(1,1), Val varchar(max))
AS
BEGIN
    DECLARE @Value varchar(max)
    WHILE @String is not null
    BEGIN
        SELECT @Value=CASE WHEN PATINDEX('%'+@Delimiter+'%',@String) >0 THEN LEFT(
          @String,PATINDEX('%'+@Delimiter+'%',@String)-1) ELSE @String END, 
          @String=CASE WHEN PATINDEX('%'+@Delimiter+'%',@String) >0 THEN SUBSTRING(
          @String,PATINDEX('%'+@Delimiter+'%',@String)+LEN(@Delimiter),LEN(@String)) ELSE NULL END
        INSERT INTO @RESULTS (Val)
        SELECT @Value
    END
RETURN
END

Now pass HTML table and execute query 

DECLARE @data varchar(Max)
SET @Data= '<table>    
            <tr><td>hello</td><td>1</td></tr>
            <tr><td>welcome</td> <td>2</td></tr> 
            </table>'

    select convert(varchar(max),[1]) as col1,[2] col2 from
    (
        select replace(b.val,'</td>','') data,rowno,id-1 as colno from
        (
            select replace( replace(a.val,'</tr>',''),'</table>','') as row,
                    row_number() over (order by a.id) as rowno 
            from dbo.parsevalues(@Data,'<tr>')  a
            where a.val like '<td>%' 
        ) as a
        cross apply  dbo.parsevalues(row,'<td>') as b 
        where  b.id <> 1
    )  as a

PIVOT
(
 max(data)
  FOR colno
  IN (
        [1],[2]
     )
) PivotTable

Happy coding!

License

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

About the Author

Aarti Meswania
Software Developer
India India
Member
It's amazing maths of technology...
Expand knowledge by sharing it.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 2 Jan 2013
Article Copyright 2013 by Aarti Meswania
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid