Please help me learn SQL! In the code below, on the last line, I have a WHERE that should filter the data according to the elements in the arrays. This works fine if the arrays have just one element, but for more it gives 0 results. The arrays come into the stored procedure from the @Region and @City parameters.
How can i make this code work with multiple elements in the arrays?
DECLARE @act nvarchar(50) = 'salesbyregionandcity';
DECLARE @Region nvarchar(MAX) = 'Marrakech-Safi,Rabat-Salé-Kénitra';
DECLARE @City nvarchar(MAX) = 'Marrakesh,Salé';
IF(LOWER(@act) = 'salesbyregionandcity')
SELECT
r.[Name] AS RegionName, x.CityName, x.Amount, x.[Year]
FROM
(
SELECT
c.IdRegion, c.[Name] AS CityName, b.Amount, b.[Year]
FROM
(
SELECT
ISNULL(c.IdCity, 1) AS IdCity, a.IdCustomerPos,
a.Amount, a.[Year]
FROM
(
SELECT
IdCustomerPos, Amount, Year([Date]) AS [Year]
FROM
Invoice
WHERE
YEAR([Date]) = YEAR(getdate())
OR YEAR([Date]) = YEAR(getdate()) - 1
)
AS a
LEFT JOIN
CustomerOffices c
ON a.IdCustomerPos = c.IdCustomer
)
AS b
LEFT JOIN
City c
ON c.Id = b.IdCity
WHERE
c.[Name] = @City
)
AS x
LEFT JOIN
Region r
ON x.IdRegion = r.Id
WHERE
r.[Name] IN (SELECT * FROM STRING_SPLIT (@Region, ','))
AND x.CityName IN (SELECT * FROM STRING_SPLIT (@City, ','))
delimitedsplit8k_lead,XML Splitter) or use a table type variable/parameter.STRING_SPLITinside the query. "Arrays" is the least of the problems, the query needs some serious cleaningWHERE c.[Name] = @City