Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- From http://stackoverflow.com/questions/2235889/conditional-sql-query
- CREATE PROCEDURE [dbo].[GetRecentlyListedProperties]
- (@location varchar(100), @city varchar(100),@propertyID int)
- As
- Begin
- DECLARE @numberOfDays int,
- @propertyCount int,
- @IsLocation bit -- looking for a location and not a city
- SET @Propertycount = 0
- SET @numberOfDays= 10
- -- CHECK TO SEE IF THERE ARE LISTINGS IN THE LAST 10 DAYS IN THE SAME LOCATION
- SELECT @PropertyCount =
- Count(*) FROM properties where location = @location and DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
- and PropertyID != @propertyID
- If(@PropertyCount = 0)
- Begin
- -- CHECK TO SEE IF THERE ARE LISTINGS IN THE LAST 10 DAYS IN THE SAME CITY
- SELECT @PropertyCount = Count(*) from properties where city = @city
- AND DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
- AND PropertyID != @propertyID
- IF(@PropertyCount = 0 )
- BEGIN
- SET @NumberOfDays = 30
- -- CHECK TO SEE IF THERE ARE LISTINGS IN THE LAST 30 DAYS IN THE SAME LOCATION
- SELECT @PropertyCount = COUNT(*) from properties where location = @location
- AND DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
- AND PropertyID != @propertyID
- IF(@PropertyCount = 0 )
- BEGIN
- -- CHECK TO SEE IF THERE ARE LISTINGS IN THE LAST 30 DAYS IN THE SAME CITY
- SELECT @PropertyCount = Count(*) from properties where city = @city
- AND DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
- AND PropertyID != @propertyID
- END
- ELSE
- SET @IsLocation = 1 --There are properties in the same location in the last 30 days
- END
- ELSE
- SET @IsLocation = 0 -- There are properties listed int he city in the last 10 days
- End
- Else
- SET @IsLocation = 1
- -- This is where the appropriate results are returned.
- IF(@IsLocation = 1)
- Begin
- SELECT * ,(SELECT AVG(PRICE) as AveragePrice
- FROM PROPERTIES
- WHERE DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
- AND Location = @Location
- AND PropertyID != @propertyID)
- FROM Properties
- WHERE DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
- AND Location = @Location
- AND PropertyID != @propertyID
- End
- ElSE
- SELECT * ,(SELECT AVG(PRICE) as AveragePrice
- FROM PROPERTIES
- WHERE DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
- AND City = @City
- AND PropertyID != @propertyID)
- FROM Properties
- WHERE DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
- AND City = @City
- AND PropertyID != @propertyID
- End
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement