Subject: Select In Statement
Posted By: mr_pc1963 Post Date: 4/18/2008 1:38:30 PM
I have a table [tbl_Controls] that contains the Field [ControlValue] nvarchar(250) (Data Example '1,2,3') w/o the '
If I have a single nuber as (Data Example '1') w/o the ', the query works correctly

I need to filter the following, The field [ProductType_ID] Integer

select ProductType_ID,Category from tbl_ProductsCategories
Where ProductType_ID in (Select Cast (ControlValue as integer) from tbl_Controls where controlid = 17)

I would greatly appreciate anyones help

Eddie Stoner
Reply By: planoie Reply Date: 4/18/2008 10:27:35 PM
You clearly aren't going to be able to convert "1,2,3" as an integer, so I can only assume what you are intending on is to be able to use the comma separated values as filter values like you would in an IN clause.  This is tricky and usually requires constructing dynamic SQL statements which isn't the most efficient.

I would question the database design.  If you need to have multiple values then why not have multiple records?  You are asking the database to store a set of data in a container intended for a single piece of data.  If you normalize it into multiple records then you can work with normal joins against a set.

-Peter
peterlanoie.blog
Reply By: Jeff Moden Reply Date: 4/19/2008 9:59:09 AM
I agree... the data should be normalized to have one row per control value... it's easier to maintain and, despite the length (# of rows) such a table can get to, it will always be faster than trying to do splits on the fly.  Lemme know if you need help converting the control table to a normalized table.

In the meantime, you can always do something like this... without dynamic SQL...

 SELECT pc.ProductType_ID, pc.Category
   FROM tbl_ProductsCategories pc
  INNER JOIN
        tbl_Controls tc
     ON tc.ControlID = 17
    AND ','+CAST(pc.ProductType_ID AS VARCHAR(10))+',' LIKE '%,'+tc.ControlValue+',%'

Like I said, that will be horribly slow compared to a properly normalized table.




--Jeff Moden

Go to topic 70423

Return to index page 1