ALTER PROCEDURE [dbo].[Expense_monthly_report] @start_date VARCHAR(100),
@end_date VARCHAR(100)
AS
BEGIN
DECLARE @SQLQuery AS NVARCHAR(max)
DECLARE @PivotColumns AS NVARCHAR(max)
SET nocount ON;
SELECT @PivotColumns = COALESCE(@PivotColumns + ',', '')
+ Quotename( date_of_expp)
FROM (SELECT DISTINCT Month(date_of_exp) AS date_of_expp
FROM [dbo].[tbl_exp_details]
WHERE date_of_exp >= @start_date
AND date_of_exp <= @end_date) AS PivotExample
SET @SQLQuery = N'SELECT p.part_id,' + @PivotColumns
+ ',total_amount FROM (SELECT part_id,month(date_of_exp) as month_of_exp,exp_amount FROM [dbo].[tbl_exp_details]) as tbl PIVOT( sum(exp_amount) FOR month_of_exp IN ('
+ @PivotColumns
+ ')) AS P join (SELECT part_id,sum(exp_amount) as total_amount FROM [dbo].[tbl_exp_details] where date_of_exp>='
+ @start_date + ' and date_of_exp<=' + @end_date
+ ' group by part_id) as la on p.part_id=la.part_id'
EXEC Sp_executesql @SQLQuery
END
我收到错误
日期与int
不兼容
。帮我找出问题。
答案 0 :(得分:1)
您尚未在动态查询中分隔日期值。
所以
date_of_exp<=' + @end_date
变为
date_of_exp<= 2017-07-19
计算结果,而int不会隐式转换为日期
date_of_exp <= 1991
使用Sp_executesql并修复此问题的正确方法是:
SET @SQLQuery = N'SELECT p.part_id,' + @PivotColumns
+ ',total_amount FROM (SELECT part_id,month(date_of_exp) as month_of_exp,exp_amount FROM [dbo].[tbl_exp_details]) as tbl PIVOT( sum(exp_amount) FOR month_of_exp IN ('
+ @PivotColumns
+ ')) AS P join (SELECT part_id,sum(exp_amount) as total_amount FROM [dbo].[tbl_exp_details] where date_of_exp>= @start_date and date_of_exp<=@end_date '
+ ' group by part_id) as la on p.part_id=la.part_id'
EXEC Sp_executesql @SQLQuery,
N'@start_date date, @end_date date',
@start_date,
@end_date