【问题标题】:Error on execute and print the SQL query in stored procedure在存储过程中执行和打印 SQL 查询时出错
【发布时间】:2015-05-22 11:36:30
【问题描述】:

我正在使用这个存储过程,但它会导致错误。

查询是

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 时转换失败。

【问题讨论】:

    标签: sql sql-server stored-procedures


    【解决方案1】:

    试试这个。您错过了 @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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-03
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 2013-04-13
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      相关资源
      最近更新 更多