根据sql server中的多个条件过滤表数据

时间:2014-01-18 06:43:48

标签: sql-server-2008

我有6个列表框和三个日期文本框,我用它来对数据库表应用条件过滤。 我需要的是,如果我只选择一个文本框或列表框值,或多个列表框值和多个日期值,我应该能够根据前端选择的过滤条件检索数据。应跳过我未选择的日期或列表框值。

我有以下查询,但它不起作用。我该如何编写查询?

SELECT (MPMST.partyname + '' + ',' + '' + MPMST.contactperson) AS NAME
      ,(MPMST.email + '' + ',' + '' + MPMST.phone) AS ContactDetail
      ,MPMST.address
      ,(MPMST.city + '' + ',' + '' + MPMST.area) AS city_area
      ,MPMST.Already_Computer
      ,MPMST.software
      ,visit_time
      ,visit_purpose
      ,interaction
FROM    MPMST
INNER
JOIN    MCall   ON  MPMST.Partycode = MCall.Partycode
WHERE  MCall.calltype IN ('SUP001')
AND MPMST.area IN ('pavai')
AND MPMST.city  IN ('mumbai')
AND MCall.Date >= CONVERT(DATETIME ,'01/01/2014' ,103)
AND MCall.Date <= CONVERT(DATETIME ,'31/01/2014' ,103) MCall.status = ''
AND MPMST.software = ''
AND MPMST.Software <> ''
AND MPMST.City IS NOT NULL
AND MPMST.Area IS NOT NULL 

1 个答案:

答案 0 :(得分:2)

如果我正确理解您的问题,那么您的解决方案是: 首先,您应该创建存储过程,如:

Create Procedure MPMST_SELECT
(
@P_calltype varchar(200) = Null,
@P_area varchar(200) = Null,
@P_city varchar(200) = Null,
@P_MCallFromDate Date = Null,
@P_MCallToDate Date = Null,
@P_software varchar(200) = Null
)
AS
Begin
SELECT (MPMST.partyname + '' + ',' + '' + MPMST.contactperson) AS NAME
      ,(MPMST.email + '' + ',' + '' + MPMST.phone) AS ContactDetail
      ,MPMST.address
      ,(MPMST.city + '' + ',' + '' + MPMST.area) AS city_area
      ,MPMST.Already_Computer
      ,MPMST.software
      ,visit_time
      ,visit_purpose
      ,interaction
FROM    MPMST
INNER
JOIN    MCall   ON  MPMST.Partycode = MCall.Partycode
WHERE  MCall.calltype ISNUll(@P_calltype,MCall.calltype)
AND MPMST.area  = ISNUll(@P_area,MPMST.area)
AND MPMST.city  = ISNULL(@P_city,MPMST.city)
AND MCall.Date between ISNULL(@P_MCallFromDate, MCall.Date)and ISNULL(@P_MCallToDate,MCall.Date)
AND MPMST.software = ISNULL(@P_software,MPMST.software)
END

现在您可以像以下一样运行此脚本:

MPMST_SELECT 'SUP001','pavai',Null,'01/01/2014','31/01/2014',Null