请考虑SQL-Server数据库中的下表:
Id ProductName Price Size
-----------------------------------
1 T-Shirt 1000 M
2 Jeans 1800 L
如何将此表转换为以下HTML字符串:
<div class='row' Id='1' size='M'>
<div class='cell'>T-Shirt</div>
<div class='cell'>1000</div>
</div>
<div class='row' Id='2' size='L'>
<div class='cell'>Jeans</div>
<div class='cell'>1800</div>
</div>
答案 0 :(得分:6)
像这样尝试:
首先是一个样机表(请下次自己做):
DECLARE @tbl TABLE(Id INT,ProductName VARCHAR(100),Price DECIMAL(10,4),Size VARCHAR(10));
INSERT INTO @tbl VALUES
(1,'T-Shirt',1000,'M')
,(2,'Jeans',1800,'L');
查询将使用FOR XML PATH
,它提供了对XML命名的最高控制
SELECT 'row' AS [@class]
,t.Id AS [@Id]
,t.Size AS [@size]
,'cell' AS [div/@class]
,t.ProductName AS [div]
,''
,'cell' AS [div/@class]
,t.Price AS [div]
FROM @tbl t
FOR XML PATH('div');
结果:
<div class="row" Id="1" size="M">
<div class="cell">T-Shirt</div>
<div class="cell">1000.0000</div>
</div>
<div class="row" Id="2" size="L">
<div class="cell">Jeans</div>
<div class="cell">1800.0000</div>
</div>
提示1:我们需要在中间使用空白,''
来开始一个新的<div>
元素。否则引擎会抛出错误。
提示2:典型的HTML表can be built with some XQuery
答案 1 :(得分:0)
@Shnugo击败了我。或者,您可以简单地执行以下操作:
DECLARE @table TABLE (ID INT, ProductName VARCHAR(100), Price INT, SIZE CHAR(1));
INSERT @table VALUES (1,'T-Shirt',1000,'M'),(2,'Jeans',1800,'L');
SELECT
'<div class="row" Id="'+LEFT(t.ID,30)+'" size="'+t.SIZE+'">
<div class="cell">'+t.ProductName+'</div>
<div class="cell">'+LEFT(t.Price,30)+'</div>
</div>'
FROM @table AS t;
哪个返回:
<div class="row" Id="1" size="M">
<div class="cell">T-Shirt</div>
<div class="cell">1000</div>
</div>
<div class="row" Id="2" size="L">
<div class="cell">Jeans</div>
<div class="cell">1800</div>
</div>