从表中选择*其中(动态条件)

时间:2012-04-22 08:26:41

标签: sql-server select

我的存储过程收到“@CatergoryIDs varchar”

@CatergoryIDs包含由“|”,

分隔的单个或多个ID

我的存储过程看起来像这样:

Select R.ID,,CategoryID, (sum(C.Rating)/Count(R.ID)) as "Rating"
    from Table1  R
    left outer join Table2 C
    ON R.ID = C.ID
    GROUP BY R.ID
    having R.CategoryID = @CatergoryID
    RETURN

1 个答案:

答案 0 :(得分:2)

您应该可以使用CHARINDEX。但是,效率非常低,最好将@CategoryID作为表变量。

SET @CatergoryID = '|'+@CatergoryID+'|';
SELECT R.ID, R.CategoryID, (SUM(C.Rating)/COUNT(R.ID)) AS Rating
    FROM Table1 AS R
    LEFT OUTER JOIN Table2 AS C
    ON R.ID = C.ID
    WHERE CHARINDEX('|'+R.CategoryID+'|', @CatergoryID)>0 
    GROUP BY R.ID, R.CategoryID