I have a task that looks like this:
OUTPUT:
I already have a working query, that looks like this:
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
)
PROBLEM:
I showed my code to my supervisor but he/she keeps saying that it can be simplified and i need to think in sets. I seem to struggle in understaning how to "think in sets" and no googling didn't help. So what can I do, I'm lost.
Try something like this:
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
This simply selects the smallest dress size, but prioritizes those that are present in the XML.
PS. It's not clear to me what you should do with the @DressID parameter.
Later edit: I have used the @DressID parameter, considering the revised question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With