使用 Dapper ORM 检查记录是否存在的最简单方法是什么?
我真的需要为我只想检查记录是否存在的查询定义 POCO 对象吗?
int id = ...
var exists = conn.ExecuteScalar<bool>("select count(1) from Table where Id=@id", new {id});
应该可以工作...
我认为这可能会减少一点开销,因为没有函数调用或数据类型转换:
int id = ...
var exists = connection.Query<object>(
"SELECT 1 WHERE EXISTS (SELECT 1 FROM MyTable WHERE ID = @id)", new { id })
.Any();
const string sql = "SELECT CAST(CASE WHEN EXISTS (SELECT 1 FROM MyTable WHERE Id = @Id) THEN 1 ELSE 0 END as BIT)";
bool exists = db.ExecuteScalar<bool>(sql, new { Id = 123 });
您可以让查询返回布尔值:
[Test]
public void TestExists()
{
var sql = @"with data as
(
select 1 as 'Id'
)
select CASE WHEN EXISTS (SELECT Id FROM data WHERE Id = 1)
THEN 1
ELSE 0
END AS result
from data ";
var result = _connection.Query<bool>(sql).FirstOrDefault();
Assert.That(result, Is.True);
}
conn.QuerySingleOrDefault<bool>("select top 1 1 from table where id=@id", new { id});
另一个选项将运行重复记录,即不查询表的 id
bool exists = connection.ExecuteScalar<int>(
"select count(1) from Table where notanId=@value", new { value = val})
> 0;
如果您需要对非唯一字段执行此类查询,您可以使用
HAVING
来处理大于 1 的计数。
SELECT 1
FROM Table
WHERE Col=@val
HAVING COUNT(1) > 0
恕我直言,
SELECT TOP(1)
比SELECT COUNT(1)
更好
bool exists = connection.Query<ValueTuple<long>>(
"SELECT top(1) Id FROM MYTABLE WHERE MYTABLE.Id=@Id",
new {Id}).Any());
ValueTuple<long>
是值类型。 Query<object>
映射到引用类型并导致装箱。
我正在使用这个语法,它对我、对 postgres 都有效。
select count(*)>0 from table_name where gid=@value;
对于甲骨文
SELECT CASE WHEN (B.C = 0) THEN 0 WHEN (B.C > 0) THEN 1 END boolean
FROM (select count(*) as c from table_name where gid=@value) B
WHERE B.C > 0;