Skip to content

Instantly share code, notes, and snippets.

@cfsamson
Last active November 2, 2019 12:01
Show Gist options
  • Save cfsamson/fb8907fdb0215d36ee0de7c7349c2e77 to your computer and use it in GitHub Desktop.
Save cfsamson/fb8907fdb0215d36ee0de7c7349c2e77 to your computer and use it in GitHub Desktop.
How to insert more than 1000 rows on mssql server and how to efficiently update many rows
use tiberius::SqlConnection;
use futures::Future;
use futures_state_stream::StateStream;
use tokio_current_thread::block_on_all;
fn main() {
init();
create();
batch_insert();
}
const CONNSTR: &str = "server=tcp:localhost,53354; integratedSecurity=true;";
fn init() {
let drop = "DROP TABLE IF EXISTS batch_test";
let fut = SqlConnection::connect(CONNSTR).and_then(|conn| {
conn.simple_exec(drop)
});
block_on_all(fut).unwrap();
}
fn create() {
let create = "
CREATE TABLE batch_test (
id int PRIMARY KEY,
price int
)
";
let fut = SqlConnection::connect(CONNSTR).and_then(|conn| {
conn.simple_exec(create)
});
block_on_all(fut).unwrap();
}
fn batch_insert() {
let mut values: String = (0..10000).map(|i| format!("({},{}),", i, i * 100)).collect();
values.pop();
let update = format!("INSERT INTO batch_test(id, price) SELECT id, price FROM (VALUES {})sub(id, price)", values);
let fut = SqlConnection::connect(CONNSTR).and_then(|conn| {
conn.simple_exec(update)
});
block_on_all(fut).unwrap();
}
-- setup
CREATE TABLE test (
id varchar(50) PRIMARY KEY,
price decimal(4, 2)
)
INSERT INTO test VALUES ('1', 10.00), ('2', 20.00)
-- How to insert more than 1000 rows
INSERT INTO test (id, price)
SELECT nid, nprice FROM (VALUES
('3',30.00),
('4',40.00)
)sub(nid, nprice)
;
-- batch insert from qry text
UPDATE test SET test.price = t2.qty
FROM
(SELECT nid, qty FROM (VALUES ('1',90.00), ('2',80.00))sub(nid, qty)) as t2
INNER JOIN test t1 on t2.nid = t1.id;
-- display
select * from test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment