我试图从表中生成 Html。为了实现这一点,我使用了函数。
桌子:
LayoutId LayoutDetailsId ParentId DetailSyntax DetailValue
--------------- --------------- --------------- --------------- ---------------
2 15 0 table htmlchild
2 16 15 tbody htmlchild
2 17 16 tr htmlchild
2 18 17 th No.
2 19 17 th Name
2 20 17 th Address
2 21 16 tr htmlchild
2 22 21 td 1
2 23 21 td Asha
2 24 21 td Flamboyan Street
2 25 16 tr htmlchild
2 26 25 td 2
2 27 25 td Jack
2 28 25 td Manggo Street
请注意,DetailValue 中的 htmlchild 类似于“HasChild”
功能:
CREATE FUNCTION FnHtmlGenerator(@layoutId BIGINT, @parentId BIGINT = 0, @prevTopLevelHtml VARCHAR(MAX) = '')
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @currentHtml VARCHAR(MAX);
DECLARE @parentTable TABLE
(
layoutDetailsId BIGINT,
parentId BIGINT,
syntax VARCHAR(50),
val VARCHAR(50)
);
INSERT INTO @parentTable
SELECT
ld.LayoutDetailsId,
ld.ParentId,
ld.DetailSyntax,
ld.DetailValue
FROM Alert.LayoutDetails ld
WHERE ld.ParentId = @parentId
AND ld.LayoutId = @layoutId;
SELECT
@currentHtml = '<' + pt.syntax + '>{0}</' + pt.syntax + '>',
@parentId = pt.layoutDetailsId
FROM @parentTable pt;
SELECT
@prevTopLevelHtml =
CASE CHARINDEX('{0}', @prevTopLevelHtml)
WHEN 0 THEN @currentHtml
ELSE STUFF(@prevTopLevelHtml, CHARINDEX('{0}', @prevTopLevelHtml), 3, @currentHtml)
END;
SELECT
@prevTopLevelHtml =
CASE
(SELECT COUNT(0)
FROM Alert.LayoutDetails ld
WHERE ld.ParentId = @parentId)
WHEN 0 THEN @prevTopLevelHtml
ELSE FnHtmlGenerator(@layoutId, @parentId, @prevTopLevelHtml)
END;
RETURN @prevTopLevelHtml;
END
结果:
html
---------------------------------------------------
<table><tbody><tr><td>{0}</td></tr></tbody></table>
问题是。我的函数只跟踪 1 条路径。第一个tr
和第一个td
甚至th
没有被追踪。如何让它追踪所有路径?