代码之家  ›  专栏  ›  技术社区  ›  vondip

tsql-使用内部存储过程作为参数is where子句

  •  1
  • vondip  · 技术社区  · 15 年前

    我正在尝试构建一个使用其他存储过程的存储过程。将其结果作为WHERE子句的一部分,出于某种原因,我收到一个错误:

    对象名“dbo.GetSuiteableCategories”无效。

    这是代码的副本:

    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 <=@priceRange 
      ORDER BY NEWID() 
     )as d
    
     union 
    
     select * from
     (
       select  TOP 1 * FROM [dbo].[products] competingproducts
       where competingproducts.categoryId =-2
       --and competingproducts.Price <=@priceRange 
       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 回复  |  直到 11 年前
        1
  •  2
  •   BenMorel Manish Pradhan    11 年前

    我将使用一个内联表值用户定义函数。或者简单地以内联方式编码,不需要重复使用

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

    但也有一些要点:

    • 我假设CategoryTable没有性别=0
    • 你的分类表中有3种性别吗?-)
    • 为什么要传入3个参数,但只使用1?请看下面
    • @sex是否映射到@gender?

    如果您对这3个参数有额外的处理,那么您将需要一个多语句表值函数,但要注意,这些操作可能会很慢。

        2
  •  2
  •   Jeremy    15 年前

    不能在select语句中直接使用存储过程的结果 您要么将结果输出到一个临时表中,要么使存储过程成为一个表值函数来完成您所做的工作。

    我认为这是有效的,但我是根据记忆来做的

    create table #tmp (blah, blah)
    
    Insert into #tmp
    exec dbo.sprocName
    
    推荐文章