查询参数化时出错

时间:2017-12-28 13:08:53

标签: sql-server stored-procedures parameters sql-server-2012

我对我创建的SQL查询的参数化有疑问。原始查询如下所示:

 <Assignment
     assignee={assignee}
     tagId={tagId && tagId.toString(16)}
     assignmentType={assignmentTypes.Reassign}
     onRequestClose={() => this.setState({isAssignmentInProgress: false})}
     onChange={onChange}
    />

它创建一个输出,其中可变数量的投资组合显示为列,每个投资组合名称下显示不同的投资组合收入部分。现在,我想使用参数来动态更改“WHERE”子句。同时,应该可以从前端(尚未确定)访问查询。为此,我尝试在存储过程中转换查询,如下所示:

DECLARE @portfolios AS NVARCHAR(MAX)    
DECLARE @Abfrage AS NVARCHAR(MAX)

SET @portfolios = STUFF((SELECT '[' + PortfolioName + '], ' FROM  tblPortfolio ORDER BY PortfolioName FOR XML PATH('')),1,5,NULL)

SELECT @portfolios = LEFT(@portfolios,(LEN(@portfolios)-1))

SET @Abfrage ='
SELECT Description, ' + @portfolios + '
FROM 
( SELECT tblReturnType.Description, tblPortfolio.PortfolioName, tblReturnAbs.Value
FROM 
tblReturnType INNER JOIN ((tblReturnAbs INNER JOIN tblPortfolio ON tblReturnAbs.PortfolioNo = tblPortfolio.PortfolioNo) INNER JOIN tblInstrument ON tblReturnAbs.InstrumentNo =tblInstrument.InstrumentNo) ON (tblReturnType.ReturnType = tblReturnAbs.ReturnType) 
WHERE (tblReturnAbs.Date BETWEEN ''01/01/17'' AND Dateadd("d",-1,''01/31/17'')) AND tblInstrument.Currency = ''EUR'' 
) AS x
PIVOT 
( 
    sum(x.Value)
    For x.PortfolioName in (' + @portfolios + ')
    ) AS piv
ORDER BY Description
'
Execute (@Abfrage)

现在,如果我尝试执行此过程并输入参数,则会出现以下错误:

  

Msg 8152,Level 16,State 10,Procedure Return_Attribution,Line 16   字符串或二进制数据将被截断。

我做了一些研究,我发现当字符串太长而无法放入数据字段时,通常会发生此错误。因为它只出现在我使用参数化程序时,我想我在定义或使用参数时犯了一个错误。任何帮助,将不胜感激。

0 个答案:

没有答案