1

我正在编写如下 SQL 查询:

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

@AreaIdList 参数将采用“1,2,3”等格式。

我想添加一条仅返回区域 id 等于@AreaIdList 中任何 id 的发票的行。

如果在 areaId 上搜索 ie,我知道如何做一个声明。现在问题出在哪里i.AreaId == areaId我有这个列表,我要比较@AreaIdList 中的每个区域 ID。

谁能告诉我你会怎么做?

4

1 回答 1

0

将您的 ID 列表解压缩到表格中并使用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) 
于 2012-04-17T06:05:56.790 回答