2015-03-19 50 views
0

我正在使用此存储过程,但它导致错误。执行时出错并在存储过程中打印SQL查询

查询是

declare @min int 
declare @mnt int 
declare @query varchar(MAx) 
declare @finmnth int 
declare @divid int 
declare @finyear nvarchar(max) 

set @divid = 0 
set @finmnth = 6 
set @finyear = '2014-15' 

begin 

    if @finmnth = 3 or @finmnth = 2 or @finmnth = 1 
     set @min = 13 
    else 
     set @min = @finmnth 

    Set @query = 'select 
        /* Cummulative Progress */ 
         isNull(CONVERT(DECIMAL(10, 3), SUM(case when month between 4 and '+cast(@finmnth AS varchar)+' and mpryear='+cast(@finyear as nvarchar)+' then (IDA+Govt+Benyfe)/100000 else 0 end),2),0) as CUTMTot 
       from 
        MPR 
       where 
        (division = '+cast(@Divid as varchar)+' OR '+cast(@Divid as varchar)+' = 0)' 
end 

exec(@query) 

错误是

消息245,级别16,状态1,第1行
转换nvarchar的值 '2013-14' 为数据类型int时 转换失败。

回答

0

试试这个。您错过了@finyear变量附加的引号。在这种情况下打印您的陈述是一个好主意:PRINT @query。你会看到你的陈述是怎样的。

DECLARE @min INT 
DECLARE @mnt INT 
DECLARE @query VARCHAR(MAX) 
DECLARE @finmnth INT 
DECLARE @divid INT 
DECLARE @finyear NVARCHAR(MAX) 

SET @divid = 0 
SET @finmnth = 6 
SET @finyear = '2014-15' 

BEGIN 

    IF @finmnth = 3 
     OR @finmnth = 2 
     OR @finmnth = 1 
     SET @min = 13 
    ELSE 
     SET @min = @finmnth 

    SET @query = 'select 
        /* Cummulative Progress */ 
         isNull(CONVERT(DECIMAL(10, 3), SUM(case when month between 4 and ' 
     + CAST(@finmnth AS VARCHAR) + ' and mpryear='''/*here*/ 
     + CAST(@finyear AS NVARCHAR) 
     + /*and here*/''' then (IDA+Govt+Benyfe)/100000 else 0 end),2),0) as CUTMTot 
       from 
        MPR 
       where 
        (division = ' + CAST(@Divid AS VARCHAR) + ' OR ' 
     + CAST(@Divid AS VARCHAR) + ' = 0)' 
END 

EXEC(@query) 
+0

感谢Giorgi其工作正常。非常感谢 – 2015-03-20 07:23:06