我有一个看起来像这样的任务:
输出:
我已经有一个有效的查询,看起来像这样:
ALTER function [dbo].[DressAvialableSizez]
(
@DressID int,
@ListXml xml = NULL
)
RETURNS TABLE
AS
RETURN
(
WITH CTE_SizeFilter as
(
SELECT Xmldata.Element.value('.','varchar(5)') AS Sizes, S.SortIndex AS FSort, S.DressID
FROM @ListXml.nodes('/list/i') AS Xmldata (Element)
INNER JOIN DressesSizes AS S ON S.DressSize = Xmldata.Element.value('.','varchar(5)')
WHERE S.DressID = @DressID
)
SELECT TOP(1) F.Sizes, F.FSort, S.DressSize, S.SortIndex, S.DressID
FROM DressesSizes AS S
LEFT JOIN CTE_SizeFilter AS F ON S.DressSize = F.Sizes
WHERE S.DressID = @DressID AND S.DressSize = IIF( EXISTS (
SELECT F.Sizes
FROM DressesSizes AS S
INNER JOIN CTE_SizeFilter AS F ON S.DressSize = F.Sizes),
F.Sizes,
S.DressSize)
order by F.FSort, S.SortIndex
)
问题:
我向我的主管展示了我的密码,但他/她一直在说可以 简化,我需要思考。我似乎很难理解如何“固定思维”,没有 谷歌搜索没有帮助。那我该怎么办,我迷路了。
答案 0 :(得分:2)
尝试这样的事情:
WITH CTE_SizeFilter as
(
SELECT Xmldata.Element.value('.','varchar(5)') AS DressSize
FROM @ListXml.nodes('/list/i') AS Xmldata (Element)
)
SELECT TOP(1) S.DressSize, S.SortIndex, S.DressID
FROM DressesSizes AS S
LEFT JOIN CTE_SizeFilter AS F ON S.DressSize = F.DressSize
WHERE S.DressID = @DressID
ORDER BY CASE WHEN F.Sizes IS NOT NULL THEN 1 ELSE 2 END, S.DressSize
这只是选择最小的着装大小,但优先考虑XML中存在的那些衣服。
PS。我不清楚您应该使用@DressID参数做什么。
稍后编辑:考虑到修订后的问题,我使用了@DressID参数。