我有一个很奇怪的问题。SELECT
我可以在语句中设置默认值吗?
在以下查询中,我希望boolItem
始终为false(不从数据库中检索)。疯狂,我知道,但是当我解释原因时,请忍受我。
SELECT id, boolItem = False
FROM MyTable;
我正在处理一个大型的现有SQL数据库和项目。我正在查询数据并将其作为Action
C#对象返回。动作可以由用户或标准动作定制。这由一个属性表示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
列)要好。
您可以选择值true
或false
使用别名来指定列名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] 删除。
我来说两句