views:

52

answers:

2

This is my logic.

I have an articles table and a matching images tables. The images are stored in binary format. Each image table has 2 instances of each image, this is because I have 2 sizes. 300 x 200 and 500 x 400 with their rows separated by ImageSize

I want to write a stored procedure that checks if ImageSize=3 is available and if not, then retrieve from ImageSize=2.

How can I set up my stored procedure to do this?

Thanks

+5  A: 

You can find the highest size image with a simple top 1:

create procedure dbo.GetImage(
    @ImageName varchar(50))
as
select  top 1 image
from    ImageTable
where   ImageName = @ImageName
order by
        ImageSize desc
Andomar
Dynamic sql is usually bad - sounds like there is no need for that now.
Hamish Grubijan
This is NOT dynamic sql, just a sql-statement (in a procedure) that uses a parameter.
Hans Kesting
+2  A: 

Andomar's response is completely valid and very elegant - if you want something more "down to earth", that takes into account there might be other number values involved in the future, try this:

CREATE PROCEDURE dbo.FetchImage(@ImageName VARCHAR(255))
AS
   IF EXISTS(SELECT * FROM dbo.ImageTable
             WHERE ImageName = @ImageName AND ImageSize = 3)
      SELECT
          Image
      FROM
          dbo.ImageTable
      WHERE
          ImageName = @ImageName AND ImageSize = 3
   ELSE
      SELECT
          Image
      FROM
          dbo.ImageTable
      WHERE
          ImageName = @ImageName AND ImageSize = 2

That basically does the same thing - but it'll continue to return the Image for ImageSize = 3 even if you suddenly also have image sizes codes of 4, 5, and so forth.

marc_s
IMHO Andomar's solution is more "down to earth" than yours as well as being more elegant.
Tom
@TOm: I don't like the fact that if some other value (like ImageSize=4) is introduced, Andomar's solution will fail. That's why I like to be more specific and clearer in my intent. Elegant is great - but "it works" (in all cases) is more important to me.
marc_s
If that were the case, surely you'd just use Andomar's solution with the addition of "AND ImageSize BETWEEN 2 and 3" to the WHERE clause??
Tom
@Tom: that might be a possibility, yes.
marc_s
I think this would be my best solution. I am not searching for the largest, I need code that can search for largest and if that fails gets the second best option. This is because I am displaying different sized based on the page am on. So I don't want to have a null image section.
Kenyana