代码之家  ›  专栏  ›  技术社区  ›  Kat Lim Ruiz

SQL Server:每个结果的大小写

  •  0
  • Kat Lim Ruiz  · 技术社区  · 7 年前

    CountryId , IsDeleted 等)无法更改的。

    所以当我这样做的时候:

    const mssql = require('mssql');
    var sqlstr =
    'select * from Country where CountryId = @countryId';
    var db = await koaApp.getDb();
    let result = await db.request()
      .input('countryId', mssql.Int, countryId)
      .query(sqlstr);
    

    我的结果对象是

    {
        CountryId: 1,
        CountryName: "Germany"
    }
    

    但我希望是这样

    {
        countryId: 1,
        countryName: "Germany"
    }
    

    我知道有一个“row”事件,但我想要更高性能的东西(因为我可能会从查询中返回几行,上面只是一个示例)。

    有什么建议吗?

    附言:我想避免这种情况 FOR JSON 语法

    2 回复  |  直到 7 年前
        1
  •  2
  •   marc_s MisterSmith    7 年前

    将此作为实际答案发布,因为它对OP有帮助:

    如果可行,您可以尝试简单地指定查询中的列:

    select 
        CountryID countryId,  
        CountryName countryName 
    from 
        Country 
    where 
        CountryId = @countryId
    

    通常,使用它不是最佳实践 select *

    一个简单的解释,在每个列名后面放一个空格和一个新名称(或者更好的做法,放在方括号内,例如 CountryName [countryName] -这允许在新名称中包含空格等字符)在从SQL返回时使用您选择的新名称对名称进行别名。

        2
  •  1
  •   Terry Lennox    7 年前

    我建议使用lodash实用程序库来转换列名,这里有一个u.camelCase函数:

    CamelCase documentation

    _.camelCase('Foo Bar');
    // => 'fooBar'
    
    _.camelCase('--foo-bar--');
    // => 'fooBar'
    
    _.camelCase('__FOO_BAR__');
    // => 'fooBar'
    

    let result = {
        CountryId: 1,
        CountryName: "Germany"
    };
    let resultCamelCase = Object.entries(result).reduce((obj,[key,value]) => {
        obj[_.camelCase(key)] = value;
        return obj;
    }, {});
    
    console.log(resultCamelCase);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
    推荐文章