DROP PROCEDURE dbo.usp_GetQueryResultsAsHTML GO CREATE PROCEDURE dbo.usp_GetQueryResultsAsHTML( @p_SQLStmt VARCHAR(8000)) AS DECLARE @Columns VARCHAR(MAX), @FinalHTMLOut VARCHAR(MAX), @ColHeader VARCHAR(MAX), @Final VARCHAR(MAX), @SQLStmt VARCHAR(MAX) -- drop temporary tables used. IF EXISTS (SELECT * FROM tempdb.sys.objects WHERE name = '##TEMPhtml1') DROP TABLE ##TEMPhtml1 IF EXISTS (SELECT * FROM tempdb.sys.objects WHERE name = '##TEMPhtml2') DROP TABLE ##TEMPhtml2 -- prepare query SET @SQLStmt = 'select * into ##tempHTML1 from (' + @p_SQLStmt + ') as T1' EXECUTE (@SQLStmt) --Prepare columns details SELECT @Columns = COALESCE(@Columns + ' + '' '' + ', '') + 'convert(varchar(100),isnull(' + column_name +','' ''))' FROM tempdb.information_schema.columns WHERE table_name='##tempHTML1' --Prepare column Header SET @ColHeader = '' SELECT @ColHeader = @ColHeader + ' ' + column_name + '' FROM tempdb.information_schema.columns WHERE table_name='##tempHTML1' SET @ColHeader=@ColHeader + '' --prepare final output SET @Final = 'Select '''' + ' + @Columns + ' '' '' into ##tempHTML2 from ##tempHTML1 ' EXECUTE( @Final) SET @FinalHTMLOut = ' ' + @ColHeader SELECT @FinalHTMLOut = @FinalHTMLOut + [] FROM ##tempHTML2 SET @FinalHTMLOut = @FinalHTMLOut + '
' -- drop temporary tables used. IF EXISTS (SELECT * FROM tempdb.sys.objects WHERE name = '##TEMPhtml1') DROP TABLE ##TEMPhtml1 IF EXISTS (SELECT * FROM tempdb.sys.objects WHERE name = '##TEMPhtml2') DROP TABLE ##TEMPhtml2 --return final output SELECT @FinalHTMLOut AS HTMLoutput --EXEC dbo.usp_GetQueryResultsAsHTML 'SELECT TOP 11 name, id, xtype, uid, info, status FROM sysobjects '