2010-05-15 57 views
1

我试图构建一个使用另一个存储过程的存储过程。将其结果作为where子句的一部分使用,由于某种原因我收到错误:tsql - 使用内部存储过程作为参数是where子句

无效的对象名称'dbo.GetSuitableCategories'。

下面是代码的副本:

select distinct top 6 * from 
(
    SELECT TOP 100 * 
    FROM [dbo].[products] products 
    where products.categoryId in 
    (select top 10 categories.categoryid from 
    [dbo].[GetSuitableCategories] 
     (
     -- @Age 
     -- ,@Sex 
     -- ,@Event 
     1, 
     1, 
     1 
    ) categories 
    ORDER BY NEWID() 
) 
    --and products.Price <[email protected] 
    ORDER BY NEWID() 
)as d 

union 

select * from 
(
    select TOP 1 * FROM [dbo].[products] competingproducts 
    where competingproducts.categoryId =-2 
    --and competingproducts.Price <[email protected] 
    ORDER BY NEWID() 
) as d 

,这里是[DBO] [GetSuitableCategories]:

if (@gender =0) 
    begin 
    select * from categoryTable categories 
    where categories.gender =3 
    end 
    else 
    begin 
    select * from categoryTable categories 
    where categories.gender = @gender 
    or categories.gender =3 
    end 

回答

2

我会用内嵌表值用户定义函数。或者干脆编写它内联没有再使用,需要

CREATE dbo.GetSuitableCategories 
      (
--parameters 
     ) 
RETURNS TABLE 
AS 
RETURN (
    select * from categoryTable categories 
    where categories.gender IN (3, @gender) 
) 

几点,但:

  • 我认为categoryTable没有性别= 0
  • 你有你的categoryTable 3分性别? :-)
  • 为什么传入3个参数但只使用1?请参阅下面请
  • @sex映射到@gender吗?

如果你在3个参数有额外的处理,那么你就需要一个多语句表值函数,但要注意这些可能会很慢

2

不能直接使用存储过程的结果在选择语句中 您必须将结果输出到临时表中,或将sproc放入表值函数中以执行您的操作。

我认为这是有效的,但我做这从内存

create table #tmp (blah, blah) 

Insert into #tmp 
exec dbo.sprocName 
+0

你也可以创建一个返回您请求,如果数据的视图所有GetSuitableCategories SP都会运行Select语句。 – heartlandcoder 2010-05-16 05:57:39

相关问题