我正在尝试使用Dapper确定是否可以将对象列表插入表中,而且还要进行某种检查以查看应包含哪些数据。
var data = new List<TestInsertDataDto>
{
new TestInsertDataDto { InsertId = 1, Value = 2 },
new TestInsertDataDto { InsertId = 2, Value = 3 },
new TestInsertDataDto { InsertId = 3, Value = 6 }
};
await connection.ExecuteAsync(@"
INSERT INTO test_data (insertid, value)
VALUES (@InsertId, @Value)
-- I'd like to do a row per row check here to determine if the row should be
-- inserted or if this row for some reason shouldn't be inserted. This check
-- requires a query on the test_data table and a join on another table.", data)
;
答案 0 :(得分:3)
您可以使用EXISTS
或NOT EXISTS
根据另一个查询有条件地插入记录。
看起来像:
INSERT INTO test_data (insertid, value)
SELECT @InsertId, @Value
WHERE EXISTS (
SELECT *
FROM test_data
WHERE -- some condition
)
答案 1 :(得分:1)
您可以做到。我建议您为此创建一个存储过程。使用dapper将参数传递给过程,然后在存储过程中尝试以下代码
INSERT INTO table (id, val) SELECT @InsertId, @Value WHERE EXISTS ( SELECT * FROM test_data WHERE -- your condition )