如何在sql server动态查询中为参数赋值

时间:2016-10-05 10:18:57

标签: sql-server sql-server-2008 tsql

您好我需要运行动态SQL查询。在那里我需要将'Sum'值添加到变量。

这是我的查询:

DECLARE @FinYear varchar(10), @TableName varchar(30), @Sql varchar(MAX)='',@FinStartDate datetime
    DECLARE @Op_P_loan numeric(9,2),@Op_R_loan numeric(9,2)`enter code here`
DECLARE CurQueryOp CURSOR FOR 
        SELECT FinDesc
        FROM FinancialYear
        WHERE FinStartDate <=@FromDate
        OPEN CurQueryOp
        FETCH NEXT FROM CurQueryOp INTO @FinYear
        WHILE @@FETCH_STATUS = 0
        BEGIN
            SELECT @TableName = name
            FROM sys.tables
            WHERE name LIKE '%TransPass%'+REPLACE(@FinYear,'-','')+'%'
            IF ISNULL(@TableName,'') <> ''
            BEGIN
                SET @Sql='SELECT '+@Op_P_loan+'='+ISNULL(@Op_P_loan,0)+'+SUM(CASE WHEN Receipt = ''P'' THEN Amount ELSE 0 END), '+
                         ' '+@Op_R_loan+'='+ISNULL(@Op_R_loan,0)+'+SUM(CASE WHEN Receipt = ''R'' THEN Amount ELSE 0 END) '+
                         'FROM '+@TableName+' '+
                         'WHERE TranDate between ''2010/04/01'' AND '''+CONVERT(VARCHAR,DATEADD(DAY,-1,@FromDate),102)+''' '+
                         'AND LedgerCode=''300'' '+
                         'AND CustomerCode='''+@CustomerCode+''' '

                EXEC(@Sql)
            END
            FETCH NEXT FROM CurQueryOp INTO @FinYear
        END
        CLOSE CurQueryOp
        DEALLOCATE CurQueryOp

当我执行此操作时,我收到以下错误:

  

将varchar转换为数据类型numeric的算术溢出错误。

1 个答案:

答案 0 :(得分:0)

您正在将@Op_P_loan和@Op_R_loan的NULL值合并,并且在这种情况下自动转换失败。试试这个:

SET @Sql='SELECT @Op_P_loan='+ISNULL(@Op_P_loan,0)+'+SUM(CASE WHEN Receipt = ''P'' THEN Amount ELSE 0 END), '+
                     ' @Op_R_loan ='+ISNULL(@Op_R_loan,0)+'+SUM(CASE WHEN Receipt = ''R'' THEN Amount ELSE 0 END) '+
                     'FROM '+@TableName+' '+
                     'WHERE TranDate between ''2010/04/01'' AND '''+CONVERT(VARCHAR,DATEADD(DAY,-1,@FromDate),102)+''' '+
                     'AND LedgerCode=''300'' '+
                     'AND CustomerCode='''+@CustomerCode+''' '