Sql 参数在存储过程中不起作用
当我为月份、年份和报表源设置参数时,它们似乎没有任何影响。在执行程序时,我仍在获取所有销售信息。有人能看出哪里出了问题吗Sql 参数在存储过程中不起作用,sql,stored-procedures,sql-server-2008-r2,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
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
您将条件检查放在错误的位置:
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
这里,这些条件(由@年
和@月
定义)仅在有折扣的情况下进行评估-如果没有折扣,这些条件将不适用
另外:这些条件实际上与折扣表的联接没有任何关系-它们仅引用基本图书销售表。您应该从连接条件中删除它们,并将它们放在常规的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
您的参数仅影响折扣表中的选择。将参数移动到where子句。首先:您使用的是什么数据库?SQL只是一种查询语言——不清楚您正在针对哪个数据库编写SQL。第二:nvarchar
不带长度的参数(在SQL Server中)的长度正好为1个字符-这是您的意图吗??我建议您始终指定一个长度!使用nvarchar(20)
(或任何合适的工具),而不仅仅是nvarchar
Microsoft SQL Server 2008 R2。啊,nvarchar应该是(255)。仍然不起作用。请看我的答案-您正在检查那些@Month
和@Year
参数是否位于错误的位置(它们与折扣表的联接无关-将它们放在正常的WHERE
子句中!)@Lebowski:如果这个答案帮助您解决了问题,请。这将表达你对那些花自己的时间帮助你的人的感激之情。