我有一個相當古怪的問題。在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);
}
表'Actions'Columns = id || description || name
表'Custom_actions'列= id || description || name || parameters
這可能嗎?它比結構上更改數據庫更好(將2個表合併為1並添加is_custom
列)。
您只需選擇值true
或false
並使用別名指定列名稱IsCustom
例如,我修改了下面的示例以顯示如何執行它(並且還從JOIN條件中刪除了AND is_custom = false/true
,因為它們似乎沒有出現任何表中的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);
}