So, imagine that you have a table Products (ID int, Name nvarchar(200))and two other tables, ProductsCategories (ProductID int, CategoryID int)and InvoiceProducts (InvoiceID int, ProductID int).
I need to write a query to create a set of products that correspond to a given set of account identifiers and category identifiers, so that the list of products matches all specified categories and all specified accounts, without returning to dynamic SQL. Imagine that I need to find a list of products that are in both categories 1 and 2, as well as in accounts 3 and 4.
At the beginning, I wrote a stored procedure that takes category identifiers and account identifiers as strings, and analyzes them in tables:
CREATE PROCEDURE dbo.SearchProducts (@categories varchar(max), @invoices varchar(max))
AS BEGIN
with catids as (select cast([value] as int) from dbo.split(@categories, ' ')),
invoiceids as (select cast([value] as int) from dbo.split(@invoices, ' '))
select * from products
END
, , . , , - , , .
: , , . ? ?
with catids as (select distinct cast([value] as int) [value] from dbo.split(@categories, ' ')),
invoiceids as (select distinct cast([value] as int) [value] from dbo.split(@invoices, ' '))
select pc.ProductID from ProductsCategories pc (nolock)
inner join catids c on c.value = pc.CategoryID
group by pc.ProductID
having COUNT(*) = (select COUNT(*) from catids)
intersect
select ip.ProductID from InvoiceProducts ip (nolock)
inner join invoiceids i on i.value = ip.InvoiceID
group by ip.ProductID
having COUNT(*) = (select COUNT(*) from invoiceids)