1

I'm writing an SQL query as follows:

ALTER proc [dbo].[Invoice_GetHomePageInvoices] (
      @AreaIdList varchar(max)
,      @FinancialYearStartDate datetime = null
,      @FinancialYearEndDate datetime = null
) as

    set nocount on

    select *
    from Invoice i
    left outer join Organisation o on i.OrganisationId = o.Id
    left outer join Area a on i.AreaId = a.Id
where i.InvoiceDate BETWEEN @FinancialYearStartDate AND @FinancialYearEndDate

The @AreaIdList parameter is going to be in the format "1,2,3" etc.

I'm wanting to add a line which will only return invoices who have area id equal to any of the ids in @AreaIdList.

I know how to do a statement if it was on areaId to search on ie. where i.AreaId == areaId problem is now I have this list I got to compare for every area Id in @AreaIdList.

Can anybody tell me how you would go about this?

Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
AnonyMouse
  • 18,108
  • 26
  • 79
  • 131
  • possible duplicate of [Parameterizing an SQL IN clause?](http://stackoverflow.com/questions/337704/parameterizing-an-sql-in-clause) – Andriy M Apr 17 '12 at 14:48

1 Answers1

0

Unpack your ID list to a table and use where AreadID in (select ID from ...)

ALTER proc [dbo].[Invoice_GetHomePageInvoices] (
       @AreaIdList varchar(max)
,      @FinancialYearStartDate datetime = null
,      @FinancialYearEndDate datetime = null
) as

set nocount on

set @AreaIdList = @AreaIdList+','
declare @T table(ID int primary key)
while len(@AreaIdList) > 1
begin
  insert into @T(ID) values (left(@AreaIdList, charindex(',', @AreaIdList)-1))
  set @AreaIdList = stuff(@AreaIdList, 1, charindex(',', @AreaIdList), '')
end

select *
from Invoice i
  left outer join Organisation o on i.OrganisationId = o.Id
  left outer join Area a on i.AreaId = a.Id
where i.InvoiceDate BETWEEN @FinancialYearStartDate AND @FinancialYearEndDate and
      i.AreadID in (select ID from @T) 
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281