在SQL语句中选择并设置值

sazr

我有一个很奇怪的问题。SELECT我可以语句中设置默认值吗?

在以下查询中,我希望boolItem始终为false(不从数据库中检索)。疯狂,我知道,但是当我解释原因时,请忍受我。

SELECT id, boolItem = False
FROM MyTable;

我正在处理一个大型的现有SQL数据库和项目。我正在查询数据并将其作为ActionC#对象返回动作可以由用户或标准动作定制。这由一个属性表示IsCustom

public class Action
{
    public int Id { get; set; }
    public bool IsCustom { get; set; }
    .....
}

在SQL数据库中,自定义操作存储在表中,custom_actions而标准操作存储在表中actions

Action使用以下代码检索和存储对象。我想使actions的查询始终将属性设置IsCustom为false。并且custom_actions查询始终将属性设置IsCustom为true。我使用的查询SELECT a.id AS Id, a.is_custom = false AS IsCustom不是有效的代码,因为该表没有一is_custom列,但是它用于演示我正在尝试做的事情。

public async Task<IEnumerable<Models.Action>> ExecuteAsync (IDbConnection conn, IDbTransaction transition, long userId)
{
    string sql = @"SELECT a.id AS Id, a.is_custom = false AS IsCustom
                   FROM actions a
                   INNER JOIN members_actions ma ON  a.id = ma.action_id AND is_custom = false
                   WHERE ma.member_id = :userId
                   UNION
                   SELECT a.id AS Id, a.is_custom = true AS IsCustom 
                   FROM custom_actions a
                   INNER JOIN members_actions ma ON  a.id = ma.action_id AND is_custom = true
                   WHERE ma.member_id = :userId;";

    return await conn.QueryAsync<Models.Action> (sql, new {userId = userId}, transition);
}

表“操作”列=表“自定义操作id || description || name
”列=id || description || name || parameters

这可能吗?它比结构更改数据库(将2个表合并为1并添加一is_custom列)要好

亚当·波拉德(Adam Porad)

您可以选择值truefalse使用别名来指定列名IsCustom

例如,我在下面修改了您的示例以显示如何执行此操作(并AND is_custom = false/true从JOIN条件中删除了,因为is_custom在这两个表中都没有显示列)。

public async Task<IEnumerable<Models.Action>> ExecuteAsync (IDbConnection conn, IDbTransaction transition, long userId)
{
    string sql = @"SELECT a.id AS Id, false AS IsCustom
                   FROM actions a
                   INNER JOIN members_actions ma ON  a.id = ma.action_id 
                   WHERE ma.member_id = :userId
                   UNION
                   SELECT a.id AS Id, true AS IsCustom 
                   FROM custom_actions a
                   INNER JOIN members_actions ma ON  a.id = ma.action_id 
                   WHERE ma.member_id = :userId;";

    return await conn.QueryAsync<Models.Action> (sql, new {userId = userId}, transition);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章