2012-04-25 90 views
0

比方说,我有一个房地产网站,在默认页面我希望让用户能够获得适合自己的参数动态SQL查询

我加 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 

谢谢你, 沙哈尔nardia。

回答

2

所有参数应

填补的值wasnt供应,其空(除非它有一个默认的VAL),然后:

,你应该使用的模式是:

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也可以在这里使用 - 但它更慢。 (比空)

+0

为什么'COALESCE()'会变慢? – 2012-04-25 09:18:10

+0

@ypercube,因为它已经过测试http://sqlserverperformance.idera.com/tsql-optimization/performance-coalesce-null/ – 2012-04-25 09:53:54

+0

该博客比较'COALESCE()'与'IS NULL'。不与'ISNULL()' – 2012-04-25 10:53:03

2

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

@PriceMin  int = 1, 

你可以设置这样的默认值,那么你只传递你想要的参数,并让剩下的采取默认值。