用动态变量舍入十进制值

时间:2018-10-07 13:38:16

标签: sql sql-server sql-function

我需要在SQL函数中根据表B中的另一列舍入表A中的列的值。

import {empty} from 'rxjs';

filterProducts(categoryId: string, questions: Question[], organisationId: string): Observable<any> {
  var formulas = this.formulaService.getFromSelectedAnswers(questions);
  let shouldFilter = this.shouldFilterProducts(categoryId, questions, formulas);
  if (!shouldFilter) return empty();

  return this.filterOrScore(categoryId, organisationId, formulas).pipe(map(products => {
    if (!products || !products.length) return empty();

    this.products.length = 0;
    this.products.push.apply(this.products, products);
    this.questionService.filterQuestionsByProducts(products, questions);      
    this.questionService.updateSession(questions);
  }));

当我将DECLARE @currencyround INT SELECT @currencyround = ISNULL(currencyround, 2) FROM dbo.PRTL_currencySettings 的值直接输入到查询中时,如下所示:

@currencyround

当我像下面这样放置SELECT CAST(POS.BALANCE AS DECIMAL(18, 2)) AS DBAmount FROM dbo.POS_SALES POS 的值时,它显示错误:

  

“ @ currencyround”附近的语法不正确。

@currencyround

3 个答案:

答案 0 :(得分:4)

您不了解什么?类型定义不允许变量。您可以使用动态SQL来做到这一点,但这似乎有些矫kill过正。

如果您关心变量的输出方式,请使用str()format()创建所需的格式。

答案 1 :(得分:4)

如果您需要特定的元数据,则可以使用动态SQL:

DECLARE @currencyround int;
SELECT @currencyround=ISNULL(currencyround,2) FROM dbo.PRTL_currencySettings;

DECLARE @sql NVARCHAR(MAX) = 
N'select CAST(POS.BALANCE AS DECIMAL(18,<currencyround>)) AS DBAmount
FROM dbo.POS_SALES POS';

SET @sql = REPLACE(@sql, '<currencyround>', @currencyround);

EXEC(@sql);

但是我个人不会编写这样的代码。我宁愿在应用程序层中格式化数字。

答案 2 :(得分:1)

如果您需要四舍五入这些值,那么如何做:

ROUND(POS.BALANCE, @currencyround)