Advertisement
Ed_Dodds

Conditional Sql Query

Jun 26th, 2013
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. From http://stackoverflow.com/questions/2235889/conditional-sql-query
  2.  
  3. CREATE PROCEDURE [dbo].[GetRecentlyListedProperties]
  4. (@location varchar(100), @city varchar(100),@propertyID int)
  5. As
  6. Begin
  7. DECLARE @numberOfDays int,
  8. @propertyCount int,
  9. @IsLocation bit -- looking for a location and not a city
  10. SET @Propertycount = 0
  11. SET @numberOfDays= 10
  12. -- CHECK TO SEE IF THERE ARE LISTINGS IN THE LAST 10 DAYS IN THE SAME LOCATION
  13. SELECT @PropertyCount =
  14. Count(*) FROM properties where location = @location and DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
  15. and PropertyID != @propertyID
  16. If(@PropertyCount = 0)
  17. Begin
  18. -- CHECK TO SEE IF THERE ARE LISTINGS IN THE LAST 10 DAYS IN THE SAME CITY
  19. SELECT @PropertyCount = Count(*) from properties where city = @city
  20. AND DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
  21. AND PropertyID != @propertyID
  22. IF(@PropertyCount = 0 )
  23. BEGIN
  24. SET @NumberOfDays = 30
  25. -- CHECK TO SEE IF THERE ARE LISTINGS IN THE LAST 30 DAYS IN THE SAME LOCATION
  26. SELECT @PropertyCount = COUNT(*) from properties where location = @location
  27. AND DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
  28. AND PropertyID != @propertyID
  29. IF(@PropertyCount = 0 )
  30. BEGIN
  31. -- CHECK TO SEE IF THERE ARE LISTINGS IN THE LAST 30 DAYS IN THE SAME CITY
  32. SELECT @PropertyCount = Count(*) from properties where city = @city
  33. AND DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
  34. AND PropertyID != @propertyID
  35. END
  36. ELSE
  37. SET @IsLocation = 1 --There are properties in the same location in the last 30 days
  38. END
  39. ELSE
  40. SET @IsLocation = 0 -- There are properties listed int he city in the last 10 days
  41. End
  42. Else
  43. SET @IsLocation = 1
  44. -- This is where the appropriate results are returned.
  45. IF(@IsLocation = 1)
  46. Begin
  47. SELECT * ,(SELECT AVG(PRICE) as AveragePrice
  48. FROM PROPERTIES
  49. WHERE DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
  50. AND Location = @Location
  51. AND PropertyID != @propertyID)
  52. FROM Properties
  53. WHERE DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
  54. AND Location = @Location
  55. AND PropertyID != @propertyID
  56. End
  57. ElSE
  58. SELECT * ,(SELECT AVG(PRICE) as AveragePrice
  59. FROM PROPERTIES
  60. WHERE DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
  61. AND City = @City
  62. AND PropertyID != @propertyID)
  63. FROM Properties
  64. WHERE DATEDIFF(day,listingtime,GETDATE()) < @numberOFDays
  65. AND City = @City
  66. AND PropertyID != @propertyID
  67. End
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement