MSSQL - NPM
MSSQL - NPM
Sign Up Sign In
mssql
10.0.1 • Public • Published 6 days ago
Readme
Code Beta
6 Dependencies
1,363 Dependents
165 Versions
node-mssql
Microsoft SQL Server client for Node.js
Installation
async () => {
try {
// make sure that any items are correctly URL encoded in the
await sql.connect('Server=localhost,1433;Database=database;U
const result = await sql.query`select * from mytable where i
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.
https://www.npmjs.com/package/mssql#output-name-type-value 2/63
9/19/23, 11:28 AM mssql - npm
options: {
encrypt: true, // for azure
trustServerCertificate: false // change to true for local dev /
}
}
async () => {
try {
// make sure that any items are correctly URL encoded in the conne
await sql.connect(sqlConfig)
const result = await sql.query`select * from mytable where id = ${
console.dir(result)
} catch (err) {
// ... error checks
}
}
Documentation
Examples
Async/Await
Promises
ES6 Tagged template literals
Callbacks
Streaming
Connection Pools
Configuration
General
Formats
Drivers
Tedious
Microsoft / Contributors Node V8 Driver for Node.js for SQL Server
https://www.npmjs.com/package/mssql#output-name-type-value 3/63
9/19/23, 11:28 AM mssql - npm
Connections
Pool Management
ConnectionPool
connect
close
Requests
Request
execute
input
output
toReadableStream
pipe
query
batch
bulk
cancel
Transactions
Transaction
begin
commit
rollback
Prepared Statements
PreparedStatement
input
output
prepare
execute
unprepare
Other
CLI
https://www.npmjs.com/package/mssql#output-name-type-value 4/63
9/19/23, 11:28 AM mssql - npm
Examples
Config
const config = {
user: '...',
password: '...',
server: 'localhost', // You can use 'localhost\\instance' to con
database: '...',
}
Async/Await
https://www.npmjs.com/package/mssql#output-name-type-value 5/63
9/19/23, 11:28 AM mssql - npm
(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_paramete
console.dir(result1)
// Stored procedure
console.dir(result2)
} catch (err) {
// ... error checks
}
})()
Promises
Queries
})
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
});
Stored procedures
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
})
https://www.npmjs.com/package/mssql#output-name-type-value 7/63
9/19/23, 11:28 AM mssql - npm
Native Promise is used by default. You can easily change this with sql.Promise =
require('myownpromisepackage') .
sql.connect(config).then(() => {
return sql.query`select * from mytable where id = ${value}`
}).then(result => {
console.dir(result)
}).catch(err => {
// ... error checks
})
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.
Callbacks
// Query
console.dir(result)
})
https://www.npmjs.com/package/mssql#output-name-type-value 8/63
9/19/23, 11:28 AM mssql - npm
// 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)
})
Streaming
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.
https://www.npmjs.com/package/mssql#output-name-type-value 9/63
9/19/23, 11:28 AM mssql - npm
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:
https://www.npmjs.com/package/mssql#output-name-type-value 10/63
9/19/23, 11:28 AM mssql - npm
rowsToProcess.push(row);
if (rowsToProcess.length >= 15) {
request.pause();
processRows();
}
});
request.on('done', () => {
processRows();
});
function processRows() {
// process rows
rowsToProcess = [];
request.resume();
}
Connection Pools
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.
https://www.npmjs.com/package/mssql#output-name-type-value 11/63
9/19/23, 11:28 AM mssql - npm
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.
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.
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.
https://www.npmjs.com/package/mssql#output-name-type-value 12/63
9/19/23, 11:28 AM mssql - npm
//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');
})
}
// 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
* If the pool does exist the config is ignored (even if it was dif
* 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()`
const close = pool.close.bind(pool);
pool.close = (...args) => {
pools.delete(name);
https://www.npmjs.com/package/mssql#output-name-type-value 14/63
9/19/23, 11:28 AM mssql - npm
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.
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.
https://www.npmjs.com/package/mssql#output-name-type-value 15/63
9/19/23, 11:28 AM mssql - npm
// in this example all integer values will return 1 more than their
sql.valueHandler.set(sql.TYPES.Int, (value) => value + 1)
Configuration
The following is an example configuration object:
const config = {
user: '...',
password: '...',
server: 'localhost',
database: '...',
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
}
}
https://www.npmjs.com/package/mssql#output-name-type-value 16/63
9/19/23, 11:28 AM mssql - npm
Formats
In addition to configuration object there is an option to pass config as a connection string.
Connection strings are supported.
Server=localhost,1433;Database=database;User Id=username;Password=pass
Driver=msnodesqlv8;Server=(local)\INSTANCE;Database=database;UID=DOMAI
Server=*.database.windows.net;Database=database;Authentication=Active
https://www.npmjs.com/package/mssql#output-name-type-value 17/63
9/19/23, 11:28 AM mssql - npm
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.
Server=*.database.windows.net;Database=database;Authentication=Active
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
Server=*.database.windows.net;Database=database;Authentication=Active
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
For more reference, you can consult here. Under the authentication.type parameter.
Drivers
Tedious
Default driver, actively maintained and production ready. Platform independent, runs
everywhere Node.js runs. Officially supported by Microsoft.
https://www.npmjs.com/package/mssql#output-name-type-value 18/63
9/19/23, 11:28 AM mssql - npm
Extra options:
options.instanceName - The instance name to connect to. The SQL Server Browser
service must be running on the database server, and UDP port 1434 on the database
server must be reachable.
options.useUTC - A boolean determining whether or not use UTC time for values
without time zone offset (default: true ).
options.encrypt - A boolean determining whether or not the connection will be
encrypted (default: true ).
options.tdsVersion - The version of TDS to use (default: 7_4 , available: 7_1 , 7_2 ,
7_3_A , 7_3_B , 7_4 ).
options.appName - Application name used for SQL server logging.
options.abortTransactionOnError - A boolean determining whether to rollback a
transaction automatically if any error is encountered during the given transaction's
execution. This sets the value for 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
https://www.npmjs.com/package/mssql#output-name-type-value 19/63
9/19/23, 11:28 AM mssql - npm
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.
Extra options:
https://www.npmjs.com/package/mssql#output-name-type-value 20/63
9/19/23, 11:28 AM mssql - npm
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.
Connections
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.
Events
connect ([callback])
Create a new connection pool. The initial probe connection is created to find out whether
the configuration is valid.
Arguments
callback(err) - A callback which is called after initial probe connection has established,
or an error has occurred. Optional. If omitted, returns Promise.
Example
https://www.npmjs.com/package/mssql#output-name-type-value 21/63
9/19/23, 11:28 AM mssql - npm
pool.connect(err => {
// ...
})
Errors
close()
Close all active connections in the pool.
Example
pool.close()
Request
Events
https://www.npmjs.com/package/mssql#output-name-type-value 22/63
9/19/23, 11:28 AM mssql - npm
Arguments
Example
// ...
})
Errors
https://www.npmjs.com/package/mssql#output-name-type-value 23/63
9/19/23, 11:28 AM mssql - npm
Arguments
Example
request.input('input_parameter', value)
request.input('input_parameter', sql.Int, value)
sql.map.register(MyClass, sql.Text)
sql.map.register(Number, sql.BigInt)
https://www.npmjs.com/package/mssql#output-name-type-value 24/63
9/19/23, 11:28 AM mssql - npm
Errors (synchronous)
NB: Do not use parameters @p{n} as these are used by the internal drivers and cause a
conflict.
Arguments
Example
request.output('output_parameter', sql.Int)
request.output('output_parameter', sql.VarChar(50), 'abc')
Errors (synchronous)
toReadableStream
Convert request to a Node.js ReadableStream
Example
https://www.npmjs.com/package/mssql#output-name-type-value 25/63
9/19/23, 11:28 AM mssql - npm
OR if you wanted to increase the highWaterMark of the read stream to buffer more rows in
memory
pipe (stream)
Sets request to stream mode and pulls all rows from all recordsets to a given stream.
Arguments
Example
Arguments
https://www.npmjs.com/package/mssql#output-name-type-value 26/63
9/19/23, 11:28 AM mssql - npm
Example
console.log(result.recordset[0].number) // return 1
// ...
})
Errors
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.
https://www.npmjs.com/package/mssql#output-name-type-value 27/63
9/19/23, 11:28 AM mssql - npm
Arguments
Example
Errors
You can enable multiple recordsets in queries with the request.multiple = true
command.
https://www.npmjs.com/package/mssql#output-name-type-value 28/63
9/19/23, 11:28 AM mssql - npm
Arguments
Example
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.
Errors
cancel()
Cancel currently executing request. Return true if cancellation packet was send
successfully.
Example
// ...
})
request.cancel()
Transaction
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.
https://www.npmjs.com/package/mssql#output-name-type-value 30/63
9/19/23, 11:28 AM mssql - npm
Example
transaction.commit(err => {
// ... error checks
console.log("Transaction committed.")
})
})
})
Aborted transactions
This example shows how you should correctly handle transaction errors when
abortTransactionOnError ( XACT_ABORT ) is enabled. Added in 2.0.
https://www.npmjs.com/package/mssql#output-name-type-value 31/63
9/19/23, 11:28 AM mssql - npm
rolledBack = true
})
new sql.Request(transaction)
.query('insert into mytable (bitcolumn) values (2)', (err, resul
// insert should fail because of invalid value
if (err) {
if (!rolledBack) {
transaction.rollback(err => {
// ... error checks
})
}
} else {
transaction.commit(err => {
// ... error checks
})
}
})
})
Events
Arguments
isolationLevel - Controls the locking and row versioning behavior of TSQL statements
issued by a connection. Optional. READ_COMMITTED by default. For possible values
see sql.ISOLATION_LEVEL .
https://www.npmjs.com/package/mssql#output-name-type-value 32/63
9/19/23, 11:28 AM mssql - npm
callback(err) - A callback which is called after transaction has began, or an error has
occurred. Optional. If omitted, returns Promise.
Example
Errors
commit ([callback])
Commit a transaction.
Arguments
callback(err) - A callback which is called after transaction has committed, or an error has
occurred. Optional. If omitted, returns Promise.
Example
transaction.commit(err => {
// ... error checks
})
})
Errors
https://www.npmjs.com/package/mssql#output-name-type-value 33/63
9/19/23, 11:28 AM mssql - npm
rollback ([callback])
Rollback a transaction. If the queue isn't empty, all queued requests will be Cancelled and
the transaction will be marked as aborted.
Arguments
callback(err) - A callback which is called after transaction has rolled back, or an error
has occurred. Optional. If omitted, returns Promise.
Example
transaction.rollback(err => {
// ... error checks
})
})
Errors
Prepared Statement
IMPORTANT: always use PreparedStatement class to create prepared statements - it
ensures that all your executions of prepared statement are executed on one connection.
Once you call prepare , a single connection is acquired from the connection pool and all
subsequent executions are executed exclusively on this connection. After you call
unprepare , the connection is then released back to the connection pool.
https://www.npmjs.com/package/mssql#output-name-type-value 34/63
9/19/23, 11:28 AM mssql - npm
If you omit the connection argument, the global connection is used instead.
Example
})
})
})
IMPORTANT: Remember that each prepared statement means one reserved connection
from the pool. Don't forget to unprepare a prepared statement when you've finished your
queries!
You can execute multiple queries against the same prepared statement but you must
unprepare the statement when you have finished using it otherwise you will cause the
connection pool to run out of available connections.
Arguments
Example
ps.input('input_parameter', sql.Int)
ps.input('input_parameter', sql.VarChar(50))
Errors (synchronous)
Arguments
Example
ps.output('output_parameter', sql.Int)
ps.output('output_parameter', sql.VarChar(50))
Errors (synchronous)
Arguments
Example
Errors
Arguments
values - An object whose names correspond to the names of parameters that were
added to the prepared statement before it was prepared.
callback(err) - A callback which is called after execution has completed, or an error has
occurred. Optional. If omitted, returns Promise.
Example
https://www.npmjs.com/package/mssql#output-name-type-value 37/63
9/19/23, 11:28 AM mssql - npm
ps.unprepare(err => {
// ... error checks
})
})
})
ps.stream = true
const request = ps.execute({param: 12345})
https://www.npmjs.com/package/mssql#output-name-type-value 38/63
9/19/23, 11:28 AM mssql - npm
ps.unprepare(err => {
// ... error checks
})
})
})
TIP: To learn more about how number of affected rows works, see section Affected Rows.
Errors
unprepare ([callback])
Unprepare a prepared statement.
Arguments
Example
ps.unprepare(err => {
// ... error checks
})
})
Errors
https://www.npmjs.com/package/mssql#output-name-type-value 39/63
9/19/23, 11:28 AM mssql - npm
CLI
If you want to add the MSSQL CLI tool to your path, you must install it globally with npm
install -g mssql .
Setup
Create a .mssql.json configuration file (anywhere). Structure of the file is the same as
the standard configuration object.
{
"user": "...",
"password": "...",
"server": "localhost",
"database": "..."
}
Example
Results in:
[[{"username":"patriksimek","password":"tooeasy"}]]
Results in:
[[{"username":"patriksimek","password":"tooeasy"}],[{"id":15,"name":
https://www.npmjs.com/package/mssql#output-name-type-value 40/63
9/19/23, 11:28 AM mssql - npm
If you omit config path argument, mssql will try to load it from current working directory.
You can override some config settings via CLI options ( --user , --password , --
server , --database , --port ).
Results in:
[[{"username":"onotheruser","password":"quiteeasy"}]]
Geography
Geography types can be constructed several different ways. Refer carefully to
documentation to verify the coordinate ordering; the ST methods tend to order
parameters as longitude (x) then latitude (y), while custom CLR methods tend to prefer to
order them as latitude (y) then longitude (x).
The query:
results in:
{
srid: 4326,
version: 2,
points: [
Point { lat: 1, lng: 1, z: null, m: null },
Point { lat: 1, lng: 3, z: null, m: null },
https://www.npmjs.com/package/mssql#output-name-type-value 41/63
9/19/23, 11:28 AM mssql - npm
NOTE: You will also see x and y coordinates in parsed Geography points, they are not
recommended for use. They have thus been omitted from this example. For compatibility,
they remain flipped (x, the horizontal offset, is instead used for latitude, the vertical), and
thus risk misleading you. Prefer instead to use the lat and lng properties.
Geometry
Geometry types can also be constructed in several ways. Unlike Geographies, they are
consistent in always placing x before y. node-mssql decodes the result of this query:
{
srid: 4326,
version: 1,
points: [
Point { x: 1, y: 1, z: null, m: null },
Point { x: 1, y: 3, z: null, m: null },
Point { x: 7, y: 3, z: null, m: null },
Point { x: 1, y: 1, z: null, m: null }
],
figures: [ { attribute: 2, pointOffset: 0 } ],
shapes: [ { parentOffset: -1, figureOffset: 0, type: 3 } ],
segments: []
}
https://www.npmjs.com/package/mssql#output-name-type-value 42/63
9/19/23, 11:28 AM mssql - npm
const tvp = new sql.Table() // You can optionally specify table type
// Add rows
tvp.rows.add('hello tvp', 777) // Values are in same order as column
https://www.npmjs.com/package/mssql#output-name-type-value 43/63
9/19/23, 11:28 AM mssql - npm
TIP: You can also create Table variable from any recordset with recordset.toTable() .
You can optionally specify table type name in the first argument.
You can clear the table rows for easier batching by using table.rows.clear()
const tvp = new sql.Table() // You can optionally specify table type
// Add rows
tvp.rows.add('hello tvp', 777) // Values are in same order as column
tvp.rows.clear()
Response Schema
An object returned from a sucessful basic query would look like the following.
{
recordsets: [
[
{
COL1: "some content",
COL2: "some more content"
}
]
],
recordset: [
{
COL1: "some content",
COL2: "some more content"
}
],
output: {},
https://www.npmjs.com/package/mssql#output-name-type-value 44/63
9/19/23, 11:28 AM mssql - npm
rowsAffected: [1]
}
Affected Rows
If you're performing INSERT , UPDATE or DELETE in a query, you can read number of
affected rows. The rowsAffected variable is an array of numbers. Each number
represents number of affected rows by a single statement.
In addition to the rowsAffected attribute on the done event, each statement will emit the
number of affected rows as it is completed.
console.log(result.rowsAffected)
})
JSON support
SQL Server 2016 introduced built-in JSON serialization. By default, JSON is returned as a
plain text in a special column named JSON_F52E2B61-18A1-11d1-B105-
00805F49916B .
Example
SELECT
1 AS 'a.b.c',
2 AS 'a.b.d',
3 AS 'a.x',
4 AS 'a.y'
FOR JSON PATH
Results in:
You can enable built-in JSON parser with config.parseJSON = true . Once you
enable this, recordset will contain rows of parsed JS objects. Given the same example,
result will look like this:
recordset = [ { a: { b: { c: 1, d: 2 }, x: 3, y: 4 } } ]
IMPORTANT: In order for this to work, there must be exactly one column named
JSON_F52E2B61-18A1-11d1-B105-00805F49916B in the recordset.
https://www.npmjs.com/package/mssql#output-name-type-value 46/63
9/19/23, 11:28 AM mssql - npm
If your queries contain output columns with identical names, the default behaviour of
mssql will only return column metadata for the last column with that name. You will
also not always be able to re-assemble the order of output columns requested.
Default behaviour:
Results in:
{
recordsets: [
[ { name: [ 'asdf', 'jkl' ], other_name: 'qwerty' } ]
],
recordset: [ { name: [ 'asdf', 'jkl' ], other_name: 'qwerty' } ],
output: {},
rowsAffected: [ 1 ]
}
You can use the arrayRowMode configuration parameter to return the row values as
arrays and add a separate array of column values. arrayRowMode can be set globally
during the initial connection, or per-request.
https://www.npmjs.com/package/mssql#output-name-type-value 47/63
9/19/23, 11:28 AM mssql - npm
console.log(result)
});
Results in:
{
recordsets: [ [ [ 'asdf', 'qwerty', 'jkl' ] ] ],
recordset: [ [ 'asdf', 'qwerty', 'jkl' ] ],
output: {},
rowsAffected: [ 1 ],
columns: [
[
{
index: 0,
name: 'name',
length: 4,
type: [sql.VarChar],
scale: undefined,
precision: undefined,
nullable: false,
caseSensitive: false,
identity: false,
readOnly: true
},
{
index: 1,
name: 'other_name',
length: 6,
type: [sql.VarChar],
scale: undefined,
precision: undefined,
nullable: false,
caseSensitive: false,
identity: false,
readOnly: true
https://www.npmjs.com/package/mssql#output-name-type-value 48/63
9/19/23, 11:28 AM mssql - npm
},
{
index: 2,
name: 'name',
length: 3,
type: [sql.VarChar],
scale: undefined,
precision: undefined,
nullable: false,
caseSensitive: false,
identity: false,
readOnly: true
}
]
]
}
When using arrayRowMode with stream enabled, the output from the recordset
event (as described in Streaming) is returned as an array of column metadata, instead of
as a keyed object. The order of the column metadata provided by the recordset event
will match the order of row values when arrayRowMode is enabled.
Results in:
{
name: {
index: 2,
https://www.npmjs.com/package/mssql#output-name-type-value 49/63
9/19/23, 11:28 AM mssql - npm
name: 'name',
length: 3,
type: [sql.VarChar],
scale: undefined,
precision: undefined,
nullable: false,
caseSensitive: false,
identity: false,
readOnly: true
},
other_name: {
index: 1,
name: 'other_name',
length: 6,
type: [sql.VarChar],
scale: undefined,
precision: undefined,
nullable: false,
caseSensitive: false,
identity: false,
readOnly: true
}
}
With arrayRowMode :
Results in:
https://www.npmjs.com/package/mssql#output-name-type-value 50/63
9/19/23, 11:28 AM mssql - npm
[
{
index: 0,
name: 'name',
length: 4,
type: [sql.VarChar],
scale: undefined,
precision: undefined,
nullable: false,
caseSensitive: false,
identity: false,
readOnly: true
},
{
index: 1,
name: 'other_name',
length: 6,
type: [sql.VarChar],
scale: undefined,
precision: undefined,
nullable: false,
caseSensitive: false,
identity: false,
readOnly: true
},
{
index: 2,
name: 'name',
length: 3,
type: [sql.VarChar],
scale: undefined,
precision: undefined,
nullable: false,
caseSensitive: false,
identity: false,
https://www.npmjs.com/package/mssql#output-name-type-value 51/63
9/19/23, 11:28 AM mssql - npm
readOnly: true
}
]
Errors
There are 4 types of errors you can handle:
Those errors are initialized in node-mssql module and its original stack may be cropped.
You can always access original error with err.originalError .
SQL Server may generate more than one error for one request so you can access
preceding errors with err.precedingErrors .
Error Codes
Each known error has name , code and message properties.
Connection
ConnectionError ETIMEOUT
timeout.
Database is
ConnectionError EALREADYCONNECTED already
connected!
Already
ConnectionError EALREADYCONNECTING connecting to
database!
https://www.npmjs.com/package/mssql#output-name-type-value 52/63
9/19/23, 11:28 AM mssql - npm
Connection not
ConnectionError ENOTOPEN
yet open.
Instance lookup
ConnectionError EINSTLOOKUP
failed.
Connection is
ConnectionError ECONNCLOSED
closed.
Transaction has
TransactionError ENOTBEGUN
not begun.
Transaction has
TransactionError EALREADYBEGUN
already begun.
Can't
commit/rollback
transaction.
TransactionError EREQINPROG
There is a
request in
progress.
Transaction has
TransactionError EABORT
been aborted.
Message from
SQL Server.
Error object
RequestError EREQUEST
contains
additional
details.
Request
RequestError ETIMEOUT
timeout.
https://www.npmjs.com/package/mssql#output-name-type-value 53/63
9/19/23, 11:28 AM mssql - npm
Invalid number
RequestError EARGS
of arguments.
SQL injection
RequestError EINJECT
warning.
No connection is
RequestError ENOCONN specified for
that request.
Invalid number
PreparedStatementError EARGS
of arguments.
SQL injection
PreparedStatementError EINJECT
warning.
Statement is
PreparedStatementError EALREADYPREPARED already
prepared.
Statement is not
PreparedStatementError ENOTPREPARED
prepared.
https://www.npmjs.com/package/mssql#output-name-type-value 54/63
9/19/23, 11:28 AM mssql - npm
Informational messages
To receive informational messages generated by PRINT or RAISERROR commands use:
info.message - Message.
info.number - The message number.
info.state - The message state, used as a modifier to the number.
info.class - The class (severity) of the message. Equal or lower than 10. Detailed
explanation can be found here.
info.lineNumber - The line number in the SQL batch or stored procedure that generated
the message. Line numbers begin at 1; therefore, if the line number is not applicable to
the message, the value of LineNumber will be 0.
info.serverName - The server name.
info.procName - The stored procedure name.
Metadata
Recordset metadata are accessible through the recordset.columns property.
https://www.npmjs.com/package/mssql#output-name-type-value 55/63
9/19/23, 11:28 AM mssql - npm
{
first: {
index: 0,
name: 'first',
length: 17,
type: [sql.Decimal],
scale: 4,
precision: 18,
nullable: true,
caseSensitive: false
identity: false
readOnly: true
},
second: {
index: 1,
name: 'second',
length: 4,
type: [sql.VarChar],
nullable: false,
caseSensitive: false
identity: false
readOnly: true
}
}
Data Types
You can define data types with length/precision/scale:
https://www.npmjs.com/package/mssql#output-name-type-value 56/63
9/19/23, 11:28 AM mssql - npm
sql.Bit
sql.BigInt
sql.Decimal ([precision], [scale])
sql.Float
sql.Int
sql.Money
sql.Numeric ([precision], [scale])
sql.SmallInt
sql.SmallMoney
sql.Real
sql.TinyInt
sql.Char ([length])
sql.NChar ([length])
sql.Text
sql.NText
sql.VarChar ([length])
sql.NVarChar ([length])
sql.Xml
sql.Time ([scale])
sql.Date
sql.DateTime
sql.DateTime2 ([scale])
https://www.npmjs.com/package/mssql#output-name-type-value 57/63
9/19/23, 11:28 AM mssql - npm
sql.DateTimeOffset ([scale])
sql.SmallDateTime
sql.UniqueIdentifier
sql.Variant
sql.Binary
sql.VarBinary ([length])
sql.Image
sql.UDT
sql.Geography
sql.Geometry
To setup MAX length for VarChar , NVarChar and VarBinary use sql.MAX length.
Types sql.XML and sql.Variant are not supported as input parameters.
SQL injection
This module has built-in SQL injection protection. Always use parameters or tagged
template literals to pass sanitized values to your queries.
Known issues
Tedious
If you're facing problems with connecting SQL Server 2000, try setting the default TDS
version to 7.1 with config.options.tdsVersion = '7_1' (issue)
https://www.npmjs.com/package/mssql#output-name-type-value 58/63
9/19/23, 11:28 AM mssql - npm
If you're executing a statement longer than 4000 chars on SQL Server 2000, always use
batch instead of query (issue)
https://www.npmjs.com/package/mssql#output-name-type-value 59/63
9/19/23, 11:28 AM mssql - npm
same as sql.close()
Bulk table inserts will attempt to coerce dates from non-Date objects if the column type
is expecting a date
Repeat calls to the global connect function ( sql.connect() ) will return the current
global connection if it exists (rather than throwing an error)
Attempting to add a parameter to queries / stored procedures will now throw an error;
use replaceInput and replaceOutput instead
Invalid isolation levels passed to Transaction s will now throw an error
ConnectionPool now reports if it is healthy or not
( ConnectionPool.healthy ) which can be used to determine if the pool is able to
create new connections or not
Pause/Resume support for streamed results has been added to the msnodesqlv8 driver
Keywords
Provenance Beta
Source Commit
github.com/tediousjs/node-mssql@c4544be
Build File
.github/workflows/nodejs.yml
Public Ledger
Transparency log entry
Share feedback
Install
npm i mssql
Repository
github.com/tediousjs/node-mssql
Homepage
github.com/tediousjs/node-mssql#readme
https://www.npmjs.com/package/mssql#output-name-type-value 61/63
9/19/23, 11:28 AM mssql - npm
Weekly Downloads
215,585
Version License
10.0.1 MIT
Last publish
6 days ago
Collaborators
Try on RunKit
Report malware
Support
https://www.npmjs.com/package/mssql#output-name-type-value 62/63
9/19/23, 11:28 AM mssql - npm
Help
Advisories
Status
Contact npm
Company
About
Blog
Press
Policies
Terms of Use
Code of Conduct
Privacy
https://www.npmjs.com/package/mssql#output-name-type-value 63/63