我需要帮助请写一个sproc,它需要一个表值参数@Locations,其Type定义如下:
CREATE TYPE [dbo].[tvpLocation] AS TABLE(
[CountryId] [int] NULL,
[ResortName] [nvarchar](100) NULL,
[Ordinal] [int] NOT NULL,
PRIMARY KEY CLUSTERED
(
[Ordinal] ASC
)WITH (IGNORE_DUP_KEY = OFF)
)
@Locations将包含至少1行。每一行都有一个非null的CountryId,并且可能有一个非null的ResortName。 每一行都有一个唯一的Ordinal,第一行为0. @Locations中CountryId和ResortName的组合将是唯一的。
sproc需要搜索以下表结构。
通过右键单击图像和查看图像,可以更好地看到图像,具体取决于您的浏览器。
现在这就是我被困住的地方,sproc应该能够找到Tours:
编辑这是我最终使用的代码,基于Anthony Faull的建议。非常感谢Anthony:
select distinct T.Id
from tblTour T
join tblTourHotel TH on TH.TourId = T.Id
join tblHotel H ON H.Id = TH.HotelId
JOIN @Locations L ON
(
(
L.Ordinal = 0
AND TH.Ordinal = 0
)
OR
(
L.Ordinal > 0
AND TH.Ordinal > 0
)
)
AND L.CountryId = H.CountryId
AND
(
L.ResortName = H.ResortName
OR L.ResortName IS NULL
)
cross apply( select COUNT(TH2.Id) AS [Count] FROM tblTourHotel TH2 where TH2.TourId = TH.TourId ) TourHotelCount
where
TourHotelCount.[Count] = @LocationCount
group by T.Id, T.TourRef, T.Description, T.DepartureDate, T.NumNights, T.DepartureAirportId, T.DestinationAirportId, T.AirlineId, T.FEPrice
having COUNT(distinct TH.Id) = @LocationCount
答案 0 :(得分:1)
WITH Matches AS
(
SELECT TH.TourId, TH.Ordinal
FROM dbo.tblTourHotel TH
WHERE EXISTS
(
SELECT 1
FROM dbo.tblHotel H
JOIN @Locations L ON
(
(
L.Ordinal = 0
AND TH.Ordinal = 0
)
OR
(
L.Ordinal > 0
AND TH.Ordinal > 0
)
)
AND L.CountryId = H.CountryId
AND
(
L.ResortName = H.ResortName
OR L.ResortName IS NULL
)
WHERE H.Id = TH.HotelId
)
)
SELECT M.TourId
FROM Matches M
WHERE
(
NOT EXISTS
(
SELECT 1
FROM @Locations L
WHERE L.Ordinal > 0
)
OR NOT EXISTS
(
SELECT 1
FROM dbo.tblTourHotel TH
WHERE TH.Ordinal > 0
AND NOT EXISTS
(
SELECT 1
FROM Matches M
WHERE M.Ordinal = TH.Ordinal
AND M.TourId = TH.TourId
)
)
)
WHERE M.Ordinal = 0
答案 1 :(得分:0)
SELECT TH.TourId
FROM dbo.tblTourHotel TH
JOIN dbo.tblHotel H on H.Id = TH.HotelId
LEFT JOIN @Locations L
ON SIGN(L.Ordinal) = SIGN(TH.Ordinal)
AND L.CountryId = H.CountryId
AND (L.ResortName = H.ResortName OR L.ResortName IS NULL)
GROUP BY TH.TourId
HAVING COUNT(H.CountryId) = COUNT(L.CountryId)