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!