动态SQL查询

时间:2012-04-25 09:00:12

标签: sql stored-procedures

假设我有一个房地产网站,在默认页面中,我想让用户获得符合其参数的帖子数量

我补充说 a link to an example image

计数器应对每个更改做出反应并自动向用户显示该数字(这将在ajax jquery中执行)

我写了一个查询,但只有在填写了所有参数的情况下它才会起作用,我想启用填写一些但仍能使计数器正常工作

这是查询

ALTER PROCEDURE shahar30_nadlan.CountPropertyResultsByquery 


@AreaID         int,
@DealID        int,
@PropertyTypeId int,
@FieldMax      int,
@FieldMin      int,
@RoomsMax      decimal,
@RoomsMin      decimal,
@PriceMax      int,
@PriceMin      int,
@ParkingSpace  bit,
@Elevator      bit,
@Aircondition  bit,
@Furniture     bit,
@Warehouse     bit,
@Balkony       bit,
@handicapped  bit, 
@Immediate    bit,
@Description  NVARCHAR(MAX)

AS
BEGIN


select count(*) from Tbl_Property
where AreaID        = @AreaID         and 
  DealID        = @DealID         and
  PropertyTypeId= @PropertyTypeId and
  Field  <= @FieldMax        and
  Field  >= @FieldMin        and
  Rooms  <= @RoomsMax        and
  Rooms  >= @RoomsMin        and
  Price  <= @PriceMax        and
  Price  >= @PriceMin       and
  ParkingSpace = @ParkingSpace   and
  Elevator = @Elevator       and
  Aircondition = @Aircondition   and
  Furniture = @Furniture      and
  Warehouse = @Warehouse      and
  Balkony = @Balkony        and
  handicapped = @handicapped    and
  [Immediate] = @Immediate      and
  Description like  '%' + @Description + '%' 

END
谢谢你, shahar nardia。

2 个答案:

答案 0 :(得分:2)

所有参数都应填写

如果某个值未提供,则其为null(除非它具有默认值),然后是:

您应该使用的模式是:

select * from myTable where 

(  @companyId  IS NULL  OR ( companyId = @companyId ))
and
 ( @Name IS NULL  OR ( Name  = @Name ))
and
...

 (   companyId  = isnull(@companyId,companyId ))
      and
  (    Name = isnull(@Name ,Name ))
      and

    ...

coalesce也可以在这里使用 - 但它的速度较慢。 (比为空)

答案 1 :(得分:2)

你尝试过可选参数吗?这是一个例子:

@PriceMin      int = 1,

你可以像这样设置默认值,然后只传递你想要的参数,剩下的就是默认值。