I have got stuck in writing the SQL stored prosedure in MS SQL Server Management Studio 2005

The table looks like following

[Quantity] | [Plant]
        10 | Apple
        20 | Carrot
        30 | Lemon
        40 | Orange

The procedure looks like that:

SELECT * 
FROM dbo.PLANTS
where [Plant] in (@Name)

What am I trying to do is set @Name='Fruits' and get all the fruits from the table plants. So I wrote something like

SELECT * 
FROM dbo.PLANTS
where [Plant] in 
(
Case
when @Name='Fruits' then ('Apple', 'Lemon', 'Orange')
)

Obviously it didn't work. Is there any way such trick may work?

Thank you in advance.

有帮助吗?

解决方案 2

You could do

SELECT * 
FROM dbo.PLANTS
where 
  (@Name='Fruits' and [Plant] in ('Apple', 'Lemon', 'Orange'))

If you'll want to select other things based on @Name, you could do that:

SELECT * 
FROM dbo.PLANTS
where (@Name='Fruits' and [Plant] in ('Apple', 'Lemon', 'Orange'))
   or (@Name='Vegetables' and [Plant] in ('Tomato', 'Onion', 'Cucumber'))

However, it's best that you make this more explicit in the data itself and add a Catergory column, as Aaron pointed out.

其他提示

You could re-write it this way:

WHERE @Name = 'Fruits' AND Plant IN ('Apple','Lemon','Orange')

But much better would be to add a category to the other table and make a simpler join, this way you don't need to keep a list of fruits and a list of veggies hard-coded in your stored procedure.

I think what you want is something like this:

SELECT *
FROM dbo.PLANTS
WHERE (@Name='Fruits' and Plant in ('Apple', 'Lemon', 'Orange')) or
      (@Name = Plant);

You don't need the case statement to generalize this.

SELECT *
FROM dbo.PLANTS
WHERE (@Name='Fruits' and Plant in ('Apple', 'Lemon', 'Orange')) or
      (@Name = 'Tropical' and Plant in ('Orange', 'Lemon', 'Mango')) or
      (@Name = Plant);

However, if you have too many choices you should put the mapping between "Name" and plants in a separate table.

SELECT * 
FROM dbo.PLANTS
where [Plant] in 
(
Case
when @Name='Fruits' then ('Apple', 'Lemon', 'Orange') end
)

have you tried putting the END keyword? or try to put a column as a category to make it more easier

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top