我想使用 SqlKata 创建和编译一个 SQL 查询,然后在其他一些函数中执行这个查询。根据文档,这并不明显,尤其是对于复杂的查询。
我曾尝试将查询转换为字符串然后运行它,但这似乎不是正确的做法,而且该字符串对于复杂的查询不能很好地编译。
public class TradeLoader : ITradeLoader
{
public SqlResult CreateTradeQuery(Target targets, Group groups, DateTime fromTime)
{
var compiler = new SqlServerCompiler();
var query = new Query().FromRaw(@"
[trades] AS t WITH (NOLOCK)
LEFT JOIN [info] AS i WITH (NOLOCK)
ON t.Id = i.Id
")
.Select("i.Name", "t.Price", "t.Volume")
.WhereTime("t.CreatedDate", ">", fromTime);
var subQuery = new Query(@"
[trades] AS t WITH (NOLOCK)
LEFT JOIN [info] AS i WITH (NOLOCK)
ON t.Id = i.Id
");
foreach (var target in targets)
{
subQuery.OrWhere(q => q.WhereIn("i.Name", groups.Keys).WhereIn("i.GroupName", target.Value));
}
query.Where(subQuery);
SqlResult result = compiler.Compile(query);
return result; // How to execute this somewhere else?
}
}
我不清楚如何使用 SqlKata.Execution 或 System.Data.SqlClient 在其他地方执行此查询。最好我应该能够在两者中运行它。