orm
The Prisma ORM: write your application in TypeScript with human-readable queries instead of SQL. Host your database on Prisma Postgres and your app on Prisma Compute.
- 48k
- TypeScript
- Apache-2.0
- 38 min ago
Microsoft SQL Server client for Node.js
Repo tediousjs/node-mssql, read from GitHub 1 min ago. tediousjs has not joined Take My Repo.
tediousjs/node-mssql is a public repo on GitHub by tediousjs. Microsoft SQL Server client for Node.js. It declares the MIT license on GitHub. It is written mainly in JavaScript, has 2,273 stars and last changed on 2026-11-22. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-22.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
Microsoft SQL Server client for Node.js
Supported TDS drivers:
npm install mssql
npm install mssql msnodesqlv8
msnodesqlv8 6 needs Node.js 22 or later. On an older Node.js, install msnodesqlv8 5 (npm install mssql msnodesqlv8@5). With msnodesqlv8 6, use its latest release, 6.2.1 or later: 6.0.0 to 6.2.0 keep hold of the connection of a stream that is paused after it is cancelled.
This package requires TCP/IP to connect to SQL Server, and you may need to enable this in your installation.
const sql = require('mssql') (async () => { try { // make sure that any items are correctly URL encoded in the connection string await sql.connect('Server=localhost,1433;Database=database;User Id=username;Password=password;Encrypt=true') const result = await sql.query`select * from mytable where id = ${value}` console.dir(result) } catch (err) { // ... error checks } })()
If you're on Windows Azure, add ?encrypt=true to your connection string. See docs to learn more.
Parts of the connection URI should be correctly URL encoded so that the URI can be parsed correctly.
Assuming you have set the appropriate environment variables, you can construct a config object as follows:
const sql = require('mssql') const sqlConfig = { user: process.env.DB_USER, password: process.env.DB_PWD, database: process.env.DB_NAME, server: 'localhost', pool: { max: 10, min: 0, idleTimeoutMillis: 30000 }, options: { encrypt: true, // for azure trustServerCertificate: false // change to true for local dev / self-signed certs } } (async () => { try { // make sure that any items are correctly URL encoded in the connection string await sql.connect(sqlConfig) const result = await sql.query`select * from mytable where id = ${value}` console.dir(result) } catch (err) { // ... error checks } })()
const sql = require('mssql/msnodesqlv8'); const config = { server: "MyServer", database: "MyDatabase", options: { trustedConnection: true, // Set to true if using Windows Authentication trustServerCertificate: true, // Set to true if using self-signed certificates }, // driver: "ODBC Driver 18 for SQL Server", // Uncomment to use specific driver }; (async () => { try { await sql.connect(config); const result = await sql.query`select TOP 10 * from MyTable`; console.dir(result); } catch (err) { console.error(err); } })();
const config = { user: '...', password: '...', server: 'localhost', // You can use 'localhost\\instance' to connect to named instance database: '...', }
const sql = require('mssql') (async function () { try { let pool = await sql.connect(config) let result1 = await pool.request() .input('input_parameter', sql.Int, value) .query('select * from mytable where id = @input_parameter') console.dir(result1) // Stored procedure let result2 = await pool.request() .input('input_parameter', sql.Int, value) .output('output_parameter', sql.VarChar(50)) .execute('procedure_name') console.dir(result2) } catch (err) { // ... error checks } })() sql.on('error', err => { // ... error handler })
const sql = require('mssql') sql.on('error', err => { // ... error handler }) sql.connect(config).then(pool => { // Query return pool.request() .input('input_parameter', sql.Int, value) .query('select * from mytable where id = @input_parameter') }).then(result => { console.dir(result) }).catch(err => { // ... error checks });
const sql = require('mssql') sql.on('error', err => { // ... error handler }) sql.connect(config).then(pool => { // Stored procedure return pool.request() .input('input_parameter', sql.Int, value) .output('output_parameter', sql.VarChar(50)) .execute('procedure_name') }).then(result => { console.dir(result) }).catch(err => { // ... error checks })
Native Promise is used by default. You can easily change this with sql.Promise = require('myownpromisepackage').
const sql = require('mssql') sql.connect(config).then(() => { return sql.query`select * from mytable where id = ${value}` }).then(result => { console.dir(result) }).catch(err => { // ... error checks }) sql.on('error', err => { // ... error handler })
All values are automatically sanitized against sql injection. This is because it is rendered as prepared statement, and thus all limitations imposed in MS SQL on parameters apply. e.g. Column names cannot be passed/set in statements using variables.
const sql = require('mssql') sql.connect(config, err => { // ... error checks // Query new sql.Request().query('select 1 as number', (err, result) => { // ... error checks console.dir(result) }) // Stored Procedure new sql.Request() .input('input_parameter', sql.Int, value) .output('output_parameter', sql.VarChar(50)) .execute('procedure_name', (err, result) => { // ... error checks console.dir(result) }) // Using template literal const request = new sql.Request() request.query(request.template`select * from mytable where id = ${value}`, (err, result) => { // ... error checks console.dir(result) }) }) sql.on('error', err => { // ... error handler })
If you plan to work with large amount of rows, you should always use streaming. Once you enable this, you must listen for events to receive data. Events must be attached before the query completes, but can be attached while in-flight.
const sql = require('mssql') sql.connect(config, err => { // ... error checks const request = new sql.Request() request.stream = true // You can set streaming differently for each request request.on('recordset', columns => { // Emitted once for each recordset in a query }) request.on('row', row => { // Emitted for each row in a recordset }) request.on('rowsaffected', rowCount => { // Emitted for each `INSERT`, `UPDATE` or `DELETE` statement // Requires NOCOUNT to be OFF (default) }) request.on('error', err => { // May be emitted multiple times }) request.on('done', result => { // Always emitted as the last one }) request.query('select * from verylargetable') // or request.execute(procedure) }) sql.on('error', err => { // ... error handler })
When streaming large sets of data you want to back-off or chunk the amount of data you're processing
to prevent memory exhaustion issues; you can use the Request.pause() function to do this. Here is
an example of managing rows in batches of 15:
let rowsToProcess = []; request.on('row', row => { rowsToProcess.push(row); if (rowsToProcess.length >= 15) { request.pause(); processRows(); } }); request.on('done', () => { processRows(); }); function processRows() { // process rows rowsToProcess = []; request.resume(); }
Nothing is emitted while the request is paused: row, recordset, info, error, rowsaffected and done
events wait until it is resumed. The msnodesqlv8 driver reads rows 50 at a time and only stops reading at the end
of a full batch, so the rows it reads before then are held until the request is resumed. A paused request that is
cancelled does not wait to be resumed: it drops the rows it holds, emits the other events it holds, and completes
with an error (ECANCEL) and done (see cancel).
An important concept to understand when using this library is Connection Pooling as this library uses connection pooling extensively. As one Node JS process is able to handle multiple requests at once, we can take advantage of this long running process to create a pool of database connections for reuse; this saves overhead of connecting to the database for each request (as would be the case in something like PHP, where one process handles one request).
With the advantages of pooling comes some added complexities, but these are mostly just conceptual and once you understand how the pooling is working, it is simple to make use of it efficiently and effectively.
To assist with pool management in your application there is the sql.connect() function that is used to connect to the global connection pool. You can make repeated calls to this function, and if the global pool is already connected, it will resolve to the connected pool. The following example obtains the global connection pool by running sql.connect(), and then runs the query against the pool.
NB: It's important to note that there can only be one global connection pool connected at a time. Providing a different connection config to the connect() function will not create a new connection if it is already connected.
const sql = require('mssql') const config = { ... } // run a query against the global connection pool function runQuery(query) { // sql.connect() will return the existing global pool if it exists or create a new one if it doesn't return sql.connect(config).then((pool) => { return pool.query(query) }) }
Awaiting or .then-ing the pool creation is a safe way to ensure that the pool is always ready, without knowing where it is needed first. In practice, once the pool is created then there will be no delay for the next connect() call.
Also notice that we do not close the global pool by calling sql.close() after the query is executed, because other queries may need to be run against this pool and closing it will add additional overhead to running subsequent queries. You should only ever close the global pool if you're certain the application is finished. Or for example, if you are running some kind of CLI tool or a CRON job you can close the pool at the end of the script.
While sql.connect() is in progress, sql.close() rejects with ECONNECTING and the global pool continues to connect. Wait for sql.connect() to finish before you call sql.close(). While sql.close() is in progress, sql.connect() creates a new global pool and does not reject with ECLOSING. If sql.connect() fails, the next sql.connect() call creates a new global pool.
The ability to call connect() and close() repeatedly on the global pool is intended to make pool management easier, however it is better to maintain your own reference to the pool, where connect() is called once, and the resulting global pool's connection promise is re-used throughout the entire application.
For example, in Express applications, the following approach uses a single global pool instance added to the app.locals so the application has access to it when needed. The server start is then chained inside the connect() promise.
const express = require('express') const sql = require('mssql') const config = {/*...*/} //instantiate a connection pool const appPool = new sql.ConnectionPool(config) //require route handlers and use the same connection pool everywhere const route1 = require('./routes/route1') const app = express() app.get('/path', route1) //connect the pool and start the web server when done appPool.connect().then(function(pool) { app.locals.db = pool; const server = app.listen(3000, function () { const host = server.address().address const port = server.address().port console.log('Example app listening at http://%s:%s', host, port) }) }).catch(function(err) { console.error('Error creating connection pool', err) });
Then the route uses the connection pool in the app.locals object:
// ./routes/route1.js const sql = require('mssql'); module.exports = function(req, res) { req.app.locals.db.query('SELECT TOP 10 * FROM table_name', function(err, recordset) { if (err) { console.error(err) res.status(500).send('SERVER ERROR') return } res.status(200).json({ message: 'success' }) }) }
For some use-cases you may want to implement your own connection pool management, rather than using the global connection pool. Reasons for doing this include:
The following code is an example of a custom connection pool implementation.
// pool-manager.js const mssql = require('mssql') const pools = new Map(); module.exports = { /** * Get or create a pool. If a pool doesn't exist the config must be provided. * If the pool does exist the config is ignored (even if it was different to the one provided * when creating the pool) * * @param {string} name * @param {{}} [config] * @return {Promise.<mssql.ConnectionPool>} */ get: (name, config) => { if (!pools.has(name)) { if (!config) { throw new Error('Pool does not exist'); } const pool = new mssql.ConnectionPool(config); // automatically remove the pool from the cache if `pool.close()` is called const close = pool.close.bind(pool); pool.close = (...args) => { pools.delete(name); return close(...args); } pools.set(name, pool.connect()); } return pools.get(name); }, /** * Closes all the pools and removes them from the store * * @return {Promise<mssql.ConnectionPool[]>} */ closeAll: () => Promise.all(Array.from(pools.values()).map((connect) => { return connect.then((pool) => pool.close()); })), };
This file can then be used in your application to create, fetch, and close pools.
const { get } = require('./pool-manager') async function example() { const pool = await get('default') return pool.request().query('SELECT 1') }
Similar to the global connection pool, you should aim to only close a pool when you know it will never be needed by the application again. Typically this will only be when your application is shutting down.
In some instances it is desirable to manipulate the record data as it is returned from the database, this may be to cast it as a particular object (eg: moment object instead of Date) or similar.
In v8.0.0+ it is possible to register per-datatype handlers:
const sql = require('mssql') // in this example all integer values will return 1 more than their actual value in the database sql.valueHandler.set(sql.TYPES.Int, (value) => value + 1) sql.query('SELECT * FROM [example]').then((result) => { // all `int` columns will return a manipulated value as per the callback above })
When a connection is acquired from the pool, it can be validated to ensure it is still usable. This is controlled by the validateConnection config option.
const config = { server: 'localhost', // ... validateConnection: true // default }
The following values are supported:
| Value | Description |
|---|---|
true (default) |
Executes SELECT 1 against the connection before handing it to the caller. This is the most thorough check — it verifies end-to-end connectivity — but adds a round-trip query for every pool acquisition. |
'socket' |
Performs a lightweight, synchronous check of the underlying connection state and TCP socket health. No SQL query is executed. This is significantly cheaper at scale and catches most failure modes (closed connections, destroyed sockets, wrong protocol state), but will not detect issues like server-side session invalidation. Tedious driver only — with msnodesqlv8, this value falls back to SELECT 1 behaviour because native ODBC connections do not expose socket-level properties. |
false |
Disables validation entirely. The connection is assumed to be healthy if it has not been flagged as closed or errored. Use this only if your application already handles stale connection errors gracefully. |
'socket' modeIf your application maintains a large connection pool and you see high volumes of SELECT 1 queries in your SQL Server monitoring, switching to 'socket' mode can dramatically reduce overhead. TCP keepalive (enabled by default in tedious at 30-second intervals) will independently detect and close dead connections over time, so the socket-level check provides a good balance between reliability and performance.
The following is an example configuration object:
const config = { user: '...', password: '...', server: 'localhost', database: '...', pool: { max: 10, min: 0, idleTimeoutMillis: 30000 } }
1433). Don't set when connecting to named instance.15000).15000). NOTE: msnodesqlv8 driver doesn't support timeouts < 1 second. When passed via connection string, the key must be request timeoutfalse). You can also enable streaming for each request independently (request.stream = true). Always set to true if you plan to work with large amount of rows.false). For more information please see section JSON support.10).0).30000).columns array. (default: false) See Handling Duplicate Column Namestrue)Complete list of pool options can be found here.
In addition to configuration object there is an option to pass config as a connection string. Connection strings are supported.
The number keys Connection Timeout, ConnectRetryInterval, Max Pool Size, Min Pool Size, Packet Size and Request Timeout must have a value that starts with a number. For a value such as abc, the parser throws an error that names the key and the value.
Server=localhost,1433;Database=database;User Id=username;Password=password;Encrypt=true
Driver=msnodesqlv8;Server=(local)\INSTANCE;Database=database;UID=DOMAIN\username;PWD=password;Encrypt=true
Encrypt takes true, yes, mandatory or 1 to encrypt, and false, no, optional or 0 to not encrypt. It also takes strict, which sets options.encrypt to 'strict' and turns on TDS 8.0 strict encryption with the tedious and MSNodeSQLv8 drivers. These values are not case sensitive. With the tedious driver, a connection that does not encrypt fails if the server requires encryption.
Several types of Azure Authentication are supported:
Server=*.database.windows.net;Database=database;Authentication=Active Directory Integrated;Client secret=clientsecret;Client Id=clientid;Tenant Id=tenantid;Encrypt=true
Note: Internally, the 'Active Directory Integrated' will change its type depending on the other parameters you add to it. On the example above, it will change to azure-active-directory-service-principal-secret because we supplied a Client Id, Client secret and Tenant Id.
If you want to utilize Authentication tokens (azure-active-directory-access-token) Just remove the unnecessary additional parameters and supply only a token parameter, such as in this example:
Server=*.database.windows.net;Database=database;Authentication=Active Directory Integrated;token=token;Encrypt=true
Finally if you want to utilize managed identity services such as managed identity service app service you can follow this example below:
Server=*.database.windows.net;Database=database;Authentication=Active Directory Integrated;msi endpoint=msiendpoint;Client Id=clientid;msi secret=msisecret;Encrypt=true
or if its managed identity service virtual machines, then follow this:
Server=*.database.windows.net;Database=database;Authentication=Active Directory Integrated;msi endpoint=msiendpoint;Client Id=clientid;Encrypt=true
We can also utilizes Active Directory Password but unlike the previous examples, it is not part of the Active Directory Integrated Authentication.
Server=*.database.windows.net;Database=database;Authentication=Active Directory Password;User Id=username;Password=password;Client Id=clientid;Tenant Id=tenantid;Encrypt=true
For more reference, you can consult here. Under the authentication.type parameter.
Default driver, actively maintained and production ready. Platform independent, runs everywhere Node.js runs. Officially supported by Microsoft.
Extra options:
conn is the configured tedious Connection. It can be used for attaching event handlers like in this example:require('mssql').connect({...config, beforeConnect: conn => { conn.once('connect', err => { err ? console.error(err) : console.log('mssql connected')}) conn.once('end', err => { err ? console.error(err) : console.log('mssql disconnected')}) }})
true).'strict' to use TDS 8.0 strict encryption (default: true). In a connection string, Encrypt=strict sets 'strict'.7_4, available: 7_1, 7_2, 7_3_A, 7_3_B, 7_4).XACT_ABORT during the initial SQL phase of a connection.Authentication:
On top of the extra options, an authentication property can be added to the pool config option
user, password, domain settings.default, ntlm, azure-active-directory-password, azure-active-directory-access-token, azure-active-directory-msi-vm, or azure-active-directory-msi-app-servicetedious driver, depends on authentication.type. For more details, check Tedious Authentication Interfacestedious does not support Windows Authentication/Trusted Connection, however the msnodesqlv8 driver does.More information about Tedious specific options: http://tediousjs.github.io/tedious/api-connection.html
Alternative driver for Windows (32 or 64-bit) or Linux/macOS (64-bit only). It's not part of the default package so it must be installed in addition. Supports Windows/Trusted Connection authentication.
To use this driver you must use this require statement:
const sql = require('mssql/msnodesqlv8')
Note: If you use import into your lib to prepare your request (const { VarChar } = require('mssql')) you also need to upgrade all your types import into your code (const { VarChar } = require('mssql/msnodesqlv8')) or a connection.on is not a function error will be thrown.
msnodesqlv8 5 and earlier round float and real values, and decimal values with more than six decimal places, to six decimal places, output parameters included, so a value such as 1e-10 is read as 0. numeric, money and smallmoney values are not affected. msnodesqlv8 6 reads them in full, as the tedious driver does; use its latest release.
Extra options:
conn is the connection configuration, that can be modified to pass extra parameters to the driver's open() method.false).'strict' to use TDS 8.0 strict encryption (default: false). 'strict' writes Encrypt=Strict to the connection string, which needs ODBC Driver 18 or later, so set driver to that driver, for example driver: 'ODBC Driver 18 for SQL Server'.true).Default connection string when connecting to port:
Driver={SQL Server Native Client 11.0};Server={#{server},#{port}};Database={#{database}};Uid={#{user}};Pwd={#{password}};Trusted_Connection={#{trusted}};
Default connection string when connecting to named instance:
Driver={SQL Server Native Client 11.0};Server={#{server}\\#{instance}};Database={#{database}};Uid={#{user}};Pwd={#{password}};Trusted_Connection={#{trusted}};
Please note that the connection string with this driver is not the same than tedious and use yes/no instead of true/false. You can see more on the ODBC documentation.
Internally, each ConnectionPool instance is a separate pool of TDS connections. Once you create a new Request/Transaction/Prepared Statement, a new TDS connection is acquired from the pool and reserved for desired action. Once the action is complete, connection is released back to the pool. Connection health check is built-in so once the dead connection is discovered, it is immediately replaced with a new one.
IMPORTANT: Always attach an error listener to created connection. Whenever something goes wrong with the connection it will emit an error and if there is no listener it will crash your application with an uncaught error.
const pool = new sql.ConnectionPool({ /* config */ })
Create a new connection pool. The initial probe connection is created to find out whether the configuration is valid.
If the pool is already connected, connect() resolves with the pool. If the pool is connecting, connect() waits for the connection attempt in progress and gets its result.
Until the pool has closed, connect() rejects with ECLOSING. Wait for close() to finish before you connect the pool again, or create a new ConnectionPool. The pool has closed when it publishes mssql:pool:close (POOL_CLOSE), just before close() completes. Thus a subscriber to that channel can connect the pool again.
Arguments
Example
const pool = new sql.ConnectionPool({ user: '...', password: '...', server: 'localhost', database: '...' }) pool.connect(err => { // ... })
Errors
ConnectionError) - Login failed.ConnectionError) - Connection timeout.ConnectionError) - Driver version not supported (msnodesqlv8 older than 2.4.8).ConnectionError) - Instance lookup failed.ConnectionError) - Socket error.ConnectionError) - Cannot connect a pool while it is closing.Close all active connections in the pool.
close() waits for running requests, open transactions and prepared statements to release their connections back to the pool. This wait has no timeout. A request on the pool, begin() or prepare() that waits for a free connection does not get one, even if you called it before close(). It fails before close() completes, or earlier if its wait for a connection times out (pool.acquireTimeoutMillis, default 30000). This error does not always have a code.
After you call close(), pool.connected is false. New work then fails with ECONNCLOSED (ConnectionError): new requests (on the pool or on an open transaction), begin(), prepare() and a prepared statement's execute().
A prepared statement or a transaction can still release its connection while the pool closes: unprepare(), commit() and rollback() work as usual. close() does not complete until every prepared statement is unprepared and every transaction has ended. With tedious, if the server rolls back a transaction, close() does not wait for the statements prepared in it (see Prepared Statement).
Until the pool has closed, connect() rejects with ECLOSING. Thus a prepared statement that you do not unprepare, or a transaction that you do not end, stops the pool from connecting again. To connect while close() waits, create a new ConnectionPool.
Example
pool.close()
Errors
ConnectionError) - Cannot close a pool while it is connecting.These properties are available on a connected ConnectionPool instance (after connect() has resolved). Before the pool has connected, and after close() has finished, size, available, pending and borrowed are 0:
Boolean - Whether the pool is able to create new connections.Number - Total number of connections in the pool (free + used + pending creation).Number - Number of free connections in the pool.Number - Number of pending connection acquisition requests.Number - Number of connections currently in use.Boolean - Whether the pool is connected.Boolean - Whether the pool is currently connecting.Parses a connection string into a configuration object. This is a static method.
Arguments
Example
const config = sql.ConnectionPool.parseConnectionString('Server=localhost,1433;Database=mydb;User Id=sa;Password=pwd')
const request = new sql.Request(/* [pool or transaction], [options] */)
If you omit pool/transaction argument, global pool is used instead.
The optional options argument allows per-request configuration overrides:
request.bulk()), which stream to completion as long as the connection is healthy. If you need to bound a bulk transfer, wrap the call with your own timer and call request.cancel().// Request with a 60-second timeout instead of the pool default const request = new sql.Request(pool, { requestTimeout: 60000 })
Note: When using the global pool, you must still pass undefined as the first argument to use options: new sql.Request(undefined, { requestTimeout: 60000 }).
Call a stored procedure.
Arguments
returnValue is also accessible as property of recordsets. Optional. If omitted, returns Promise.Example
const request = new sql.Request() request.input('input_parameter', sql.Int, value) request.output('output_parameter', sql.Int) request.execute('procedure_name', (err, result) => { // ... error checks console.log(result.recordsets.length) // count of recordsets returned by the procedure console.log(result.recordsets[0].length) // count of rows contained in first recordset console.log(result.recordset) // first recordset from result.recordsets console.log(result.returnValue) // procedure return value console.log(result.output) // key/value collection of output values console.log(result.rowsAffected) // array of numbers, each number represents the number of rows affected by executed statemens // ... })
Errors
RequestError) - Message from SQL ServerRequestError) - A parameter value is not valid for its type.RequestError) - Procedure name or parameter type is not a valid identifier. See Identifiers.RequestError) - Cancelled.RequestError) - Request timeout.RequestError) - No connection is specified for that request.ConnectionError) - Connection not yet open.ConnectionError) - Connection is closed.TransactionError) - Transaction has not begun.TransactionError) - Can't acquire connection for the request. There is another request in progress.TransactionError) - Transaction was aborted (by user or because of an error).Add an input parameter to the request.
Arguments
undefined and NaN values are automatically converted to null values.Example
request.input('input_parameter', value) request.input('input_parameter', sql.Int, value)
JS Data Type To SQL Data Type Map
String -> sql.NVarCharNumber -> sql.IntBoolean -> sql.BitDate -> sql.DateTimeBuffer -> sql.VarBinarysql.Table -> sql.TVPDefault data type for unknown object is sql.NVarChar.
When a Number value is provided without an explicit type, the library inspects the value to choose the best SQL type:
sql.Intsql.BigIntsql.FloatJavaScript bigint primitives follow the same range logic (sql.Int for values within the 32-bit signed range, sql.BigInt otherwise).
You can define your own type map.
sql.map.register(MyClass, sql.Text)
You can also overwrite the default type map.
sql.map.register(Number, sql.BigInt)
Errors (synchronous)
RequestError) - Invalid number of arguments.RequestError) - Parameter name is not a valid identifier. See Identifiers.NB: Do not use parameters @p{n} as these are used by the internal drivers and cause a conflict.
Add an output parameter to the request.
Arguments
undefined and NaN values are automatically converted to null values. Optional.Example
request.output('output_parameter', sql.Int) request.output('output_parameter', sql.VarChar(50), 'abc')
Errors (synchronous)
RequestError) - Invalid number of arguments.RequestError) - Parameter name is not a valid identifier. See Identifiers.Replace an existing input parameter on the request. If the parameter was previously added with input(), it is removed and re-added with the new type and value. Useful when building queries dynamically or re-using a Request object.
Arguments
Unlike input(), replaceInput() requires an explicit SQL type — auto type inference is not supported.
Example
request.input('myval', sql.Int, 1) request.replaceInput('myval', sql.Int, 2)
Replace an existing output parameter on the request.
Arguments
Example
request.output('myval', sql.Int) request.replaceOutput('myval', sql.BigInt)
Convert request to a Node.js ReadableStream
Example
const { pipeline } = require('stream') const request = new sql.Request() const readableStream = request.toReadableStream() pipeline(readableStream, transformStream, writableStream) request.query('select * from mytable')
OR if you wanted to increase the highWaterMark of the read stream to buffer more rows in memory
const { pipeline } = require('stream') const request = new sql.Request() const readableStream = request.toReadableStream({ highWaterMark: 100 }) pipeline(readableStream, transformStream, writableStream) request.query('select * from mytable')
The readable stream is destroyed with the request's first error. Later errors are still emitted on the request, but not on the stream.
If the readable stream is destroyed before the request finishes (for example because a later stream in the pipeline failed), the request still runs to the end and the rows it has left are discarded. Call request.cancel() to stop it early.
With msnodesqlv8 before 5.6 that cancel does not stop it. The request is resumed as soon as its stream is destroyed, so that it does not keep its connection, and those versions can only cancel a paused request.
Sets request to stream mode and pulls all rows from all recordsets to a given stream.
Arguments
Example
const request = new sql.Request() request.pipe(stream) request.query('select * from mytable') stream.on('error', err => { // ... }) stream.on('finish', () => { // ... })
The stream is destroyed with the request's first error, so listen for error on it as above. It does not emit finish after an error. The request still runs to the end, and its remaining rows are discarded.
If the stream fails or closes before the request finishes, or was already destroyed, the request also runs to the end and its remaining rows are discarded, rather than waiting for a stream that will not read any more. Call request.cancel() to stop it early, bearing in mind the msnodesqlv8 caveat under toReadableStream.
pipe() passes errors only to the stream it is given. If you pipe through more streams after that one, use stream.pipeline() with toReadableStream instead, so that every error reaches you:
const { pipeline } = require('stream') const request = new sql.Request() pipeline(request.toReadableStream(), transformStream, writableStream, err => { // ... }) request.query('select * from mytable')
Execute the SQL command. To execute commands like create procedure or if you plan to work with local temporary tables, use batch instead.
Arguments
Example
const request = new sql.Request() request.query('select 1 as number', (err, result) => { // ... error checks console.log(result.recordset[0].number) // return 1 // ... })
Errors
RequestError) - Request timeout.RequestError) - Message from SQL ServerRequestError) - A parameter value is not valid for its type.RequestError) - Cancelled.RequestError) - No connection is specified for that request.ConnectionError) - Connection not yet open.ConnectionError) - Connection is closed.TransactionError) - Transaction has not begun.TransactionError) - Can't acquire connection for the request. There is another request in progress.TransactionError) - Transaction was aborted (by user or because of an error).RequestError) - Parameter type is not a valid identifier. See Identifiers.const request = new sql.Request() request.query('select 1 as number; select 2 as number', (err, result) => { // ... error checks console.log(result.recordset[0].number) // return 1 console.log(result.recordsets[0][0].number) // return 1 console.log(result.recordsets[1][0].number) // return 2 })
NOTE: To get number of rows affected by the statement(s), see section Affected Rows.
Execute the SQL command. Unlike query, it doesn't use sp_executesql, so is not likely that SQL Server will reuse the execution plan it generates for the SQL. Use this only in special cases, for example when you need to execute commands like create procedure which can't be executed with query. Also you should use this if you plan to work with local temporary tables (more information here).
NOTE: Table-Valued Parameter (TVP) is not supported in batch.
Arguments
Example
const request = new sql.Request() request.batch('create procedure #temporary as select * from table', (err, result) => { // ... error checks })
Errors
RequestError) - Request timeout.RequestError) - Message from SQL ServerRequestError) - A parameter value is not valid for its type.RequestError) - Cancelled.RequestError) - No connection is specified for that request.ConnectionError) - Connection not yet open.ConnectionError) - Connection is closed.TransactionError) - Transaction has not begun.TransactionError) - Can't acquire connection for the request. There is another request in progress.TransactionError) - Transaction was aborted (by user or because of an error).RequestError) - Parameter type is not a valid identifier. See Identifiers.Perform a bulk insert.
Arguments
sql.Table instance.Example
const table = new sql.Table('table_name') // or temporary table, e.g. #temptable table.create = true table.columns.add('a', sql.Int, {nullable: true, primary: true}) table.columns.add('b', sql.VarChar(50), {nullable: false}) table.rows.add(777, 'test') const request = new sql.Request() request.bulk(table, (err, result) => { // ... error checks })
IMPORTANT: Always indicate whether the column is nullable or not!
TIP: If you set table.create to true, module will check if the table exists before it start sending data. If it doesn't, it will automatically create it. You can specify primary key columns by setting primary: true to column's options. Primary key constraint on multiple columns is supported.
TIP: You can also create Table variable from any recordset with recordset.toTable(). You can optionally specify table type name in the first argument.
TIP: A VarChar, NVarChar or VarBinary column declared without a length (e.g. sql.NVarChar) is created as max when table.create is set, and the tedious driver loads it as max. It does so whether or not the table already existed, so when table.create is set for an existing table, give such a column its length if the table's column is sized (it loads faster) or a sql_variant (which cannot hold a max value). Without table.create, the tedious driver needs a column declared as max (e.g. sql.NVarChar(sql.MAX)) to bulk load into an existing varchar(max), nvarchar(max) or varbinary(max) column. Xml, UDT, Geography and Geometry columns are loaded as max unless you give them a length.
Errors
RequestError) - Table name must be specified for bulk insert.RequestError) - Request timeout.RequestError) - Message from SQL ServerRequestError) - Cancelled.RequestError) - No connection is specified for that request.ConnectionError) - Connection not yet open.ConnectionError) - Connection is closed.TransactionError) - Transaction has not begun.TransactionError) - Can't acquire connection for the request. There is another request in progress.TransactionError) - Transaction was aborted (by user or because of an error).RequestError) - Table name, column name or parameter type is not a valid identifier. See Identifiers.Cancel currently executing request. Return true if cancellation packet was send successfully.
Example
const request = new sql.Request() request.query('waitfor delay \'00:00:05\'; select 1 as number', (err, result) => { console.log(err instanceof sql.RequestError) // true console.log(err.message) // Cancelled. console.log(err.code) // ECANCEL // ... }) request.cancel()
A cancelled stream emits an error event with code ECANCEL, followed by done.
With the msnodesqlv8 driver, a request that is already running can only be cancelled from msnodesqlv8 5.6. Earlier versions can cancel a paused stream, but let any other running request run to the end and complete as if cancel() had not been called. A paused stream is cancelled once the driver stops reading, at the end of a batch of 50 rows or the start of the next result set.
Before msnodesqlv8 6, that includes a stream paused before its query reaches its first result set, as toReadableStream() leaves one until it is read. Cancelling it while msnodesqlv8 is still working through the statements ahead of that result set can crash the process, so the cancel waits for them: they run to the end and keep their effects, however long they take. The request timeout ends the wait if it is at least a second. With requestTimeout: 0, or anything under a second, which msnodesqlv8 takes as no timeout, nothing ends it. msnodesqlv8 6 cancels such a stream at once.
A query that ends before the cancel takes effect, or times out, completes as cancelled, after emitting any error it ended with.
IMPORTANT: always use Transaction class to create transactions - it ensures that all your requests are executed on one connection. Once you call begin, a single connection is acquired from the connection pool and all subsequent requests (initialized with the Transaction object) are executed exclusively on this connection. After you call commit or rollback, connection is then released back to the connection pool.
const transaction = new sql.Transaction(/* [pool], [options] */)
If you omit connection argument, global connection is used instead.
The optional options argument allows per-transaction configuration overrides (e.g. { requestTimeout: 60000 }). These are inherited by any requests created from this transaction unless overridden at the request level. Note that the timeout applies to data requests only, not to the begin/commit/rollback operations themselves.
Example
const transaction = new sql.Transaction(/* [pool] */) transaction.begin(err => { // ... error checks const request = new sql.Request(transaction) request.query('insert into mytable (mycolumn) values (12345)', (err, result) => { // ... error checks transaction.commit(err => { // ... error checks console.log("Transaction committed.") }) }) })
Transaction can also be created by const transaction = pool.transaction(). Requests can also be created by const request = transaction.request().
Aborted transactions
This example shows how you should correctly handle transaction errors when abortTransactionOnError (XACT_ABORT) is enabled. Added in 2.0.
const transaction = new sql.Transaction(/* [pool] */) transaction.begin(err => { // ... error checks let rolledBack = false transaction.on('rollback', aborted => { // emited with aborted === true rolledBack = true }) new sql.Request(transaction
tediousjs/node-mssql is a public repo on GitHub by tediousjs. Microsoft SQL Server client for Node.js.
It declares the MIT license on GitHub.
Its maker tagged it for macOS, Windows and Linux, or as Docker or cross-platform. That is declared by the maker; Take My Repo has not tested it.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-11-22. GitHub counts 24 open issues and pull requests. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
The Prisma ORM: write your application in TypeScript with human-readable queries instead of SQL. Host your database on Prisma Postgres and your app on Prisma Compute.
Reverse engineer anything with agents, from app behavior down to native binaries.
The flexible backend for all your projects 🐰 Turn your DB into a headless CMS, admin panels, or apps with a custom UI, instant APIs, auth & more.
freeCodeCamp.org's open-source codebase and curriculum. Learn math, programming, and computer science for free.
Free, simple, and intuitive online database diagram editor and SQL generator.
This page is also available as structured data, with the same sources and dates.
/api/v1/resources/gh/tediousjs/node-mssqlTake My Repo has not tested this on your machine. Requirements come from the project's own documentation.