以下代码可以正常工作,并将表转换为HTML。它以HTML表格的形式给出结果,但我想将其分配给变量
如何在下面的代码中将输出分配给变量。
CREATE PROC dbo.usp_ConvertQuery2HTMLTable (
@SQLQuery NVARCHAR(3000))
AS
BEGIN
DECLARE @columnslist NVARCHAR (1000) = ''
DECLARE @restOfQuery NVARCHAR (2000) = ''
DECLARE @DynTSQL NVARCHAR (3000)
DECLARE @FROMPOS INT
DECLARE @out table
(
out nvarchar(max)
)
SET NOCOUNT ON
SELECT @columnslist += 'ISNULL (' + NAME + ',' + '''' + ' ' + '''' + ')' + ','
FROM sys.dm_exec_describe_first_result_set(@SQLQuery, NULL, 0)
SET @columnslist = left (@columnslist, Len (@columnslist) - 1)
SET @FROMPOS = CHARINDEX ('FROM', @SQLQuery, 1)
SET @restOfQuery = SUBSTRING(@SQLQuery, @FROMPOS, LEN(@SQLQuery) - @FROMPOS + 1)
SET @columnslist = Replace (@columnslist, '),', ') as TD,')
SET @columnslist += ' as TD'
SET @DynTSQL = CONCAT (
'SELECT (SELECT '
, @columnslist
,' '
, @restOfQuery
,' FOR XML RAW (''TR''), ELEMENTS, TYPE) AS ''TBODY'''
,' FOR XML PATH (''''), ROOT (''TABLE'')'
)
PRINT @DynTSQL
EXEC (@DynTSQL)
SET NOCOUNT OFF
END
答案 0 :(得分:0)
通常,您有2个选择。
exec()
本身在执行文字或变量时不返回任何内容,但是您可以将其产生的行集用作insert
语句的源:
-- Option 1
declare @t table (X xml);
declare @Ret xml;
insert into @t (X)
exec('select top 1 * from sys.objects o for xml raw(''TR''), elements, type;');
select top (1) @Ret = t.X from @t t;
select @Ret as [Option1];
go
sys.sp_executesql
正如Peter在评论中建议的那样,您可以从exec
切换到sp_executesql
系统存储过程,该存储过程提供了输出参数的附加功能:
-- Option 2
declare @s nvarchar(max) = N'set @A = (select top 1 * from sys.objects o for xml raw(''TR''), elements, type);';
declare @Ret xml;
exec sys.sp_executesql @s, N'@A xml = null output', @A = @Ret output;
select @Ret as [Option2];
go