views:

32

answers:

2

Hi, I am sure the title of my question doesn't make much sense. But here is what I'm trying to achieve. I have table with different stories(columns are StoryID, StoryTitle, StoryDesc, StoryCategory), so each story can belong to a category. for example category1, category2,.... category10. I am in the need of a SP, where i specify the categories as parameters(multiple categories, in CSV format or XML) and the SP will return the stories belong to that categories.

I'm not sure what would be the best way to do this in one SP call. Any pointers will be appreciated.

thank you

+1  A: 

Call your stored procedure passing the Categories parameters as input parameters.

Inside the procedure's SQL code filter it with:

Select * from Stories where StoryCategoy = category1 OR StoryCategory = category2, etc...

This link will provide you with a better way of doing this...

Passing Arrays to SQL Stored Procedures in C# ASP .NET

Oh, this one is better yet:

Passing lists to SQL Server 2005 with XML Parameters

Some code to ilustrate:

DECLARE @categoryIds xml
SET @categoryIds ='<Categories><id>17</id><id>83</id><id>88</id></Categories>'

SELECT
ParamValues.ID.value('.','VARCHAR(20)')
FROM @categoryIds.nodes('/Categories/id') as ParamValues(ID)

Which gives us the following three rows:

17
83
88
Leniel Macaferi
well, i dont want to pass 10 parameters if i need stored from 10 categories. i need some way to pass only one parameter(an XML where i specify all the categories, or CSV)
Joe
cool thanks, that will help.
Joe
@Joe: If you know you need to pass an XML, what stops you? Just pass it and use OPENXML in your query.
Tomek Szpakowicz
+1 for the XML approach (which is what I've been using for years for exactly this issue) - as an aside, you can effectively pass a whole table with a display value, as well as Id, which can save a join later on if you so desire
Rowland Shaw
@ tomekszpakowicz , i did, but i wanted to know if there is any better approach. thanks
Joe
+1  A: 
  1. Create a temporary table

    create table #MySp_Categories (
        categoryId int not null primary key
    )
    

    Insert category list into it and call your procedure (MySp). In MySp join with #MySp_Categories. After procedure finishes drop #MySp_Categories.

    Slightly complicated protocol, but works.

  2. Encode list of categories as XML and pass varchar parameter containing XML to your procedure. In procedure use OPENXML in your query.

Tomek Szpakowicz