5

我正在使用节点 mssql

我的查询文件如下

BEGIN TRANSACTION
DECLARE @status NVARCHAR(30);
SET @status = 'create';
DECLARE @i UNIQUEIDENTIFIER;
SET @i = NEWID();
DECLARE @t DATETIME2;
SET @t = SYSUTCDATETIME();
IF NOT EXISTS( 
    SELECT * FROM user WHERE email = @email AND company_id= @company_id
) BEGIN
SET @i = NEWID();
INSERT INTO user (comapny_id, id, email, password) VALUES ( @company_id, @i, @email, @password);
INSERT INTO user_transaction( id, date, type) VALUES ( @i, @t, @status);
SELECT @i as 'id', @email as 'email';
END ELSE BEGIN
SELECT NULL as 'id', @email as 'email';
END
COMMIT TRANSACTION

createuser在 query.js 文件中的查询是

 datastore.getQueryFromSqlFile('create_user', (err: any, query: string) => {
    if (err) {
        done(err);
    } else {
        var request = new sql.Request(connectionOrTransaction);
        request.input('email', sql.NVarChar(200), email);
        request.input('password', sql.NVarChar(200), some_password);
        request.input('company_id', sql.UniqueIdentifier, company_id);
        request.query(query, function (err, data) {});

现在我需要修改这些以插入从 CSV 文件导入的大量用户数据(> 20000 个条目)我正在考虑做类似的事情

 async.mapSeries(Object.keys(users), function (item, callback) {
     query.createuser(email, company_id, function (err, data) {
         callback(err, err ? 'Error message: ' + data : data);        
     });
 }, function (err, results) {
 })

但这效率不高,因为我得到连接超时。增加connectionTimeoutrequestTimeout在配置文件中并没有多大帮助。

对于每次尝试大约 20000-40000 个条目的批量插入,我怎样才能使我的查询更快?

4

1 回答 1

1

For me it looks like a job for a prepared statement.

var ps = new sql.PreparedStatement();
ps.input('email', sql.VarChar);
ps.input('password', sql.VarChar);
ps.input('company_id', sql.Int);
ps.prepare(" ... your sql ... ", function(err) {
    // ... error checks

    // users must be an array of users
    async.mapSeries(users, function(user, next) {
        ps.execute({email: user.email, password: user.password, company_id: user.company_id}, next);
    }, function(err) {
        // ... error checks

        ps.unprepare(function(err) {
            // ... error checks

            // done !
        });
    });
});

Every execute is called as a single request, so you should not be timeouted by requestTimeout. connectionTimeout is something that only affect connecting phase. Once you're connected to db, only requestTimeout matters.

于 2014-10-14T08:41:28.580 回答