参数在存储过程中不起作用

时间:2014-03-07 08:53:29

标签: sql stored-procedures sql-server-2008-r2

当我为月,年和报告来源设置参数时,它们似乎没有任何影响。在运行程序时我仍然获得所有销售。谁能看到什么错了?

ALTER PROCEDURE [dbo].[ddsDiscount] 
   @month INT, 
   @year INT, 
   @report_source nvarchar
AS 
   SELECT 
      isa.identifiers                           AS ISBN, 
      isa.sales_date                            AS DATO,
      isa.quantity                              AS ANTALL,
      bk.title                                  AS Tittel, 
      BV.name                                   AS BUTIKK, 
      BB.name                                   AS Forlag, 
      COALESCE(id.sales_price, isa.sales_price) AS SalesPrice 
   FROM   
      book_sales AS isa 
   LEFT JOIN 
      discount AS id ON isa.identifiers = id.identifiers 
                     AND isa.sales_date BETWEEN id.from_date AND id.to_date 
                     AND Month(isa.sales_date) = @month 
                     AND Year(isa.sales_date) = @year 
   LEFT OUTER JOIN 
      books AS BK ON BK.book_id = isa.book_id 
   LEFT OUTER JOIN 
      store AS BV ON bv.store_id = isa.store_id 
   LEFT OUTER JOIN 
      publisher AS BB ON bb.publisher_id = bk.publisher_id 
   LEFT OUTER JOIN 
      book_contributor AS BC ON BC.book_id = isa.book_id 
                       AND isa.report_source = @report_source 

2 个答案:

答案 0 :(得分:1)

您正在检查条件是否错误:

   FROM   
      book_sales AS isa 
   LEFT JOIN 
      discount AS id ON isa.identifiers = id.identifiers 
                     AND isa.sales_date BETWEEN id.from_date AND id.to_date 
                     AND Month(isa.sales_date) = @month 
                     AND Year(isa.sales_date) = @year 

此处,如果 折扣,那么这些条件(由@YEAR@MONTH定义)评估 - 如果没有,这些条件将被应用。

另外:这些条件实际上与discount表的JOIN没有任何关系 - 它们引用基础Book_sales表。您应该从JOIN条件中删除它们并将它们放在常规的WHERE子句中:

 SELECT 
      isa.identifiers                           AS ISBN, 
      isa.sales_date                            AS DATO,
      isa.quantity                              AS ANTALL,
      bk.title                                  AS Tittel, 
      BV.name                                   AS BUTIKK, 
      BB.name                                   AS Forlag, 
      COALESCE(id.sales_price, isa.sales_price) AS SalesPrice 
   FROM   
      book_sales AS isa 
   LEFT JOIN 
      discount AS id ON isa.identifiers = id.identifiers 
                     AND isa.sales_date BETWEEN id.from_date AND id.to_date 
   LEFT OUTER JOIN 
      books AS BK ON BK.book_id = isa.book_id 
   LEFT OUTER JOIN 
      store AS BV ON bv.store_id = isa.store_id 
   LEFT OUTER JOIN 
      publisher AS BB ON bb.publisher_id = bk.publisher_id 
   LEFT OUTER JOIN 
      book_contributor AS BC ON BC.book_id = isa.book_id 
                       AND isa.report_source = @report_source 
   WHERE
      Month(isa.sales_date) = @month 
      AND Year(isa.sales_date) = @year 

答案 1 :(得分:1)

您的参数仅影响折扣表中的选择。将参数移动到where子句。