我想解决一个类似的问题,即根据字段的值创建 tr 类,但给出的解决方案和 FOR EXPLICIT 都不起作用。我的项目使用 Data-Table 和 Twitter Bootstrap CSS 版本来设置 HTML 表格的样式。这是对我有用的解决方案:
DECLARE @tab varchar(max),
@header varchar(8000),
@fields varchar(8000),
@sql varchar(8000)
DECLARE @rtab TABLE (html varchar(max))
SET @fields = '[field 1], [field 2], [field 3]'
SELECT @sql = 'WITH cte (SELECT * FROM table)
SELECT CAST ((
SELECT CASE
WHEN [CriteriaField] = ''Value1'' THEN ''error''
WHEN [CriteriaField] = ''Value2'' THEN ''success''
WHEN [CriteriaField] = ''Value3'' THEN ''warning''
ELSE NULL END
AS [@class], (
SELECT ' + REPLACE(@fields, ',', ' AS td,') + ' AS td' + '
FOR XML RAW(''''), ELEMENTS)
FROM cte
FOR XML PATH(''tr'')) AS nvarchar(max))'
INSERT INTO @rtab EXEC(@sql)
SELECT @tab = @tab + REPLACE(REPLACE(REPLACE(REPLACE(html, '<', '<'), '>', '>'), '&gt;', '>'), '&lt;', '<') --Restore SQL Server's replacement tags.
SELECT @tab = REPLACE(@tab, '&', '&') --Restore replacement ampersands (anchor links in the data)
SELECT @header = REPLACE(@fields, ',', '</th><th>')
SELECT @header = '<th>' + @header + '</th>'
SELECT @header = '<tr>' + @header + '</tr>'
SELECT @header = REPLACE(REPLACE(@header, '[', ''), ']', '')
SELECT @tab = '<thead>' + @header + '</thead><tbody>' + @tab + '</tbody></table>'
SELECT @tab = '<table id="data-table" class="table table-bordered">' + @tab
SELECT @tab