How to use mssql

Comprehensive mssql code examples:

How to use mssql.MAX:

249
250
251
252
253
254
255
256
257
258
  Numeric: mssql.Numeric,
  NVarChar: mssql.NVarChar,
  Real: mssql.Real,
  SmallInt: mssql.SmallInt,
  UniqueIdentifier: mssql.UniqueIdentifier,
  MAX: mssql.MAX
},
adminSchema: '[mtc_admin]',
initPool: async function initPool () {
  const pool = poolService.createPool(roles.teacher)

How to use mssql.prepareRecordForSQL:

670
671
672
673
674
675
676
677
678
679
) => {
    if (recordSet._isPreparedForSQL) {
        return;
    }
    recordSet.forEach((record) => {
        sql.prepareRecordForSQL(
            record,
            recordSchema,
            addValues4NotNullableFields,
            addMissingFields,

How to use mssql.binToHexString:

474
475
476
477
478
479
480
481
482
483
        if (nullable) {
            return 'NULL';
        }
        if (!default_) return null;
    }
    return sql.binToHexString(value);
case sql.UDT:
case sql.Geography:
case sql.Geometry:
case sql.Variant:

How to use mssql.getRecordValuesForSQL:

250
251
252
253
254
255
256
257
258
259
        .join(',')))
        .join(`)\n,(`)})`;
    return `INSERT INTO ${schemaAndTable} (${insertFieldsList}) ${addOutputInserted ? ' OUTPUT inserted.* ' : ''} VALUES ${values}`;
},
getUpdateSQL (record) {
    const recordForSQL = sql.getRecordValuesForSQL(record, this.schema);
    const setArray = [];
    updateFields.forEach((fName) => {
        if (recordForSQL[fName] !== undefined) {
            setArray.push(`[${fName}] = ${recordForSQL[fName]}`);

How to use mssql.globalConnection:

9
10
11
12
13
14
15
16
17
18
var flickUser = require('./flickUser');
var StatsD = require('statsd-client');

var statsD = StatsD.globalStatsD;

//var connection = mssql.globalConnection;
function flickSqlServer() {

    function doFlickChangeList(property, oldObj, objForDb, defaultVal) {
        if (oldObj[property] === undefined && oldObj.hasOwnProperty(property) && defaultVal !== undefined) {  /// If a default is specified then use that

How to use mssql.errorHandler:

80
81
82
83
84
85
86
87
88
89
request.input('userId', mssql.UniqueIdentifier, userId);
request.query(sql, function (err, recordset) {
    if (statsD) {
        statsD.timing('flick.doGetFlickById', dbStartTime);
    }
    if (err) { mssql.errorHandler(err); err.code = 'F04021'; callback(err, undefined); return; }

    recordset.forEach(function (record) {
        for (key in record) { /// Wierd thing where userId comes out as a two row array. 
            if (key === 'userId' && Array.isArray(record[key])) {

How to use mssql.Real:

133
134
135
136
137
138
139
140
141
142
  break;
case 'nvarchar':
  type = mssql.NVarChar(columnProperty.CHARACTER_MAXIMUM_LENGTH);
  break;
case 'real':
  type = mssql.Real();
  break;
case 'text':
  type = mssql.Text();
  break;

How to use mssql.Text:

136
137
138
139
140
141
142
143
144
145
  break;
case 'real':
  type = mssql.Real();
  break;
case 'text':
  type = mssql.Text();
  break;
case 'timestamp':
  type = mssql.Time(mssql.MAX);
  break;

How to use mssql.getValueForSQL:

513
514
515
516
517
518
519
520
521
522
 * @param {*} value
 * @param {dbFieldSchema} fieldSchema
 * @returns {String|Number}
 */
sql.serialize = (value, fieldSchema) => {
    const val = sql.getValueForSQL(value, fieldSchema);
    if (val == null || val === 'NULL') {
        return null;
    }
    if (typeof val === 'number') {

How to use mssql.Time:

139
140
141
142
143
144
145
146
147
148
  break;
case 'text':
  type = mssql.Text();
  break;
case 'timestamp':
  type = mssql.Time(mssql.MAX);
  break;
case 'uniqueidentifier':
  type = mssql.UniqueIdentifier();
  break;

How to use mssql.Xml:

152
153
154
155
156
157
158
159
160
161
case 'xml':
  if (currentValue.includes('<?xml')) {
    currentValue = currentValue.substr(currentValue.indexOf('?>') + 2,
      currentValue.length);
  }
  type = mssql.Xml();
  break;
default:
  type = mssql.VarChar(columnProperty.CHARACTER_MAXIMUM_LENGTH);
  break;

How to use mssql.DateTime:

16
17
18
19
20
21
22
23
24
var udtCommercialRelease = new sql.Table();
// Las columnas deben corresponder con las creadas en la base de datos.   
udtCommercialRelease.columns.add('Id_Item', sql.VarChar(50));  
udtCommercialRelease.columns.add('Id_Country', sql.VarChar(10));
udtCommercialRelease.columns.add('Id_Status_Commercial_Release', sql.SmallInt(2));
udtCommercialRelease.columns.add('Final_Effective_Date', sql.DateTime(8));
udtCommercialRelease.columns.add('Modify_By', sql.VarChar(50));
udtCommercialRelease.columns.add('Modify_Date', sql.DateTime(8));
udtCommercialRelease.columns.add('Modify_IP', sql.VarChar(20));

How to use mssql.Date:

315
316
317
318
319
320
321
322
323
324
  break
case 'number':
  type = mssql.Decimal(param.maxLength, param.decimals)
  break
case 'date':
  type = mssql.Date
  break
case 'datetime':
  if (param.timezone === 'ignore') {
    type = mssql.DateTime2

How to use mssql.SmallDateTime:

90
91
92
93
94
95
96
97
98
99
case 'sql.Time':             return sql.Time ;
case 'sql.Date':             return sql.Date ;
case 'sql.DateTime':         return sql.DateTime ;
case 'sql.DateTime2':        return sql.DateTime2;
case 'sql.DateTimeOffset':   return sql.DateTimeOffset;
case 'sql.SmallDateTime':    return sql.SmallDateTime;
case 'sql.UniqueIdentifier': return sql.UniqueIdentifier ;
case 'sql.Binary':           return sql.Binary;
case 'sql.VarBinary':        return sql.VarBinary;
case 'sql.Image':            return sql.Image;

How to use mssql.ISOLATION_LEVEL:

11
12
13
14
15
16
17
18
19
20
// Refresh with a serializable isolation level so that refresh is prevented if the table is in use.
// If the table is in use and table lock acquisition fails, the function invocation will fail.
// In most cases function invocation will be retried automatically and should succeed.  In rare
// cases where successive retries fail, the message that triggers the function invocation will be
// placed on a dead letter queue.  In this case, manual intervention will be required.
await doInTransaction(refreshInTransaction, context, `The ${refreshData.csvSourceFile} refresh has failed with the following error:`, sql.ISOLATION_LEVEL.SERIALIZABLE, refreshData)

// Transaction 2
// If a rollback has occurred, workflow refresh and message replay should not occur.
if (refreshData.workflowRefreshCsvType && refreshData.refreshRollbackRequested === false) {

How to use mssql.s:

355
356
357
358
359
360
361
362
363
364
switch (type) {
    case 'json':
        if (Array.isArray(value) || typeof value === 'object') {
            value = JSON.stringify(value);
        }
        return sql.s(value, nullable, length, default_, noQuotes, escapeOnlySingleQuotes);
    case 'string':
    case sql.Char:
    case sql.NChar:
    case sql.Text:

How to use mssql.bit:

15
16
17
18
19
20
21
22
23
    this.types = {
        INT: sql.Int,
        DECIMAL: sql.Decimal(18, 5),
        STRING: sql.VarChar(8000),
        DATE: sql.DateTime,
        BIT: sql.bit
    }
    this.connection = new sql.Connection(connectionString);
};

How to use mssql.Binary:

92
93
94
95
96
97
98
99
100
101
case 'sql.DateTime':         return sql.DateTime ;
case 'sql.DateTime2':        return sql.DateTime2;
case 'sql.DateTimeOffset':   return sql.DateTimeOffset;
case 'sql.SmallDateTime':    return sql.SmallDateTime;
case 'sql.UniqueIdentifier': return sql.UniqueIdentifier ;
case 'sql.Binary':           return sql.Binary;
case 'sql.VarBinary':        return sql.VarBinary;
case 'sql.Image':            return sql.Image;
case 'sql.UDT':              return sql.UDT ;
case 'sql.Geography':        return sql.Geography;

How to use mssql.NChar:

80
81
82
83
84
85
86
87
88
89
case 'sql.SmallInt':         return sql.SmallInt ;
case 'sql.SmallMoney':       return sql.SmallMoney;
case 'sql.Real':             return sql.Real ;
case 'sql.TinyInt':          return sql.TinyInt ;
case 'sql.Char':             return sql.Char ;
case 'sql.NChar':            return sql.NChar;
case 'sql.Text':             return sql.Text ;
case 'sql.NText':            return sql.NText;
case 'sql.VarChar':          return sql.VarChar ;
case 'sql.NVarChar':         return sql.NVarChar ;

How to use mssql.Geography:

96
97
98
99
100
101
102
103
104
105
        case 'sql.UniqueIdentifier': return sql.UniqueIdentifier ;
        case 'sql.Binary':           return sql.Binary;
        case 'sql.VarBinary':        return sql.VarBinary;
        case 'sql.Image':            return sql.Image;
        case 'sql.UDT':              return sql.UDT ;
        case 'sql.Geography':        return sql.Geography;
        case 'sql.Geometry':         return sql.Geometry ;
        default:                     return sql.VarChar;
    }
}

How to use mssql.TinyInt:

135
136
137
138
139
140
141
142
143
144
#getParamProcedureType = (typeName) => {
    let type = null;
    
    switch (typeName.toLocaleLowerCase()) {            
        case 'tinyint':
            type = mssql.TinyInt;
            
            break;
        case 'smallint':
            type = mssql.SmallInt;

How to use mssql.SmallMoney:

167
168
169
170
171
172
173
174
175
176
case 'money':
    type = mssql.Money;
    
    break;
case 'smallmoney':
    type = mssql.SmallMoney;
                    
    break;

case 'datetime':

How to use mssql.SmallInt:

139
140
141
142
143
144
145
146
147
148
case 'tinyint':
    type = mssql.TinyInt;
    
    break;
case 'smallint':
    type = mssql.SmallInt;
    
    break;
case 'int':
    type = mssql.Int;

How to use mssql.NVARCHAR:

129
130
131
132
133
134
135
136
137
138
    return res.status(400).json({ message: 'Invalid request' });
}
const request1 = new sql.Request(connection);
const result1 = await request1.query(
    'INSERT INTO ManufacturerMaster (manufacturerid, manufacturername, logoid) VALUES (@manufacturerid, @manufacturername, @logoid)',
    sql.NVARCHAR(50), manufacturerid,
    sql.NVARCHAR(50), manufacturername,
    sql.INT, logoid
);
const request2 = new sql.Request(connection);

How to use mssql.Geometry:

46
47
48
49
50
51
52
53
54
55
        Binary: sql.Binary,
        VarBinary: sql.VarBinary,
        Image: sql.Image,
        UDT: sql.UDT,
        Geography: sql.Geography,
        Geometry: sql.Geometry
},
object: null,
getOutput: (name) => {
        if (name && req.object.parameters[name]) {

How to use mssql.Money:

163
164
165
166
167
168
169
170
171
172
case 'float':
    type = mssql.Float;

    break;
case 'money':
    type = mssql.Money;
    
    break;
case 'smallmoney':
    type = mssql.SmallMoney;

How to use mssql.Image:

57
58
59
60
61
62
63
64
65
66
  nchar: mssql.NChar,
  nvarchar: mssql.NVarChar,
  ntext: mssql.NText,
  binary: mssql.Binary,
  varbinary: mssql.VarBinary,
  image: mssql.Image
};

const dataCall = {
  decimal: ['NUMERIC_PRECISION', 'NUMERIC_SCALE'],

How to use mssql.dbo:

100
101
102
103
104
105
106
107
108
##DBO RecordSet##

数据库操作类,需要传入`connect`连接对象

``` javascript
var dbo = new mssql.dbo(connect);
```

###dbo.insert(table, datas[, callback])###

How to use mssql.DateTimeOffset:

119
120
121
122
123
124
125
126
127
128
table.columns.add('school_id', sql.Int, { nullable: false })
table.create = false
table.columns.add('foreName', sql.NVarChar, { length: 128 })
table.columns.add('lastName', sql.NVarChar, { length: 128 })
table.columns.add('gender', sql.Char, { length: 1, nullable: false })
table.columns.add('dateOfBirth', sql.DateTimeOffset(3), { nullable: false })
table.columns.add('upn', sql.Char(13), { nullable: false })

for (let schoolIdx = 0; schoolIdx < schoolCount; schoolIdx++) {
  for (let pupilIndex = 0; pupilIndex < pupilCountPerSchool; pupilIndex++) {

How to use mssql.DateTime2:

0
1
2
3
4
5
6
7
8
9
'use strict';

var sql = require('mssql');

exports.string = sql.NText;
exports.dateTime = sql.DateTime2;
exports.regExp = sql.NText;
exports.function = sql.NText;
exports.object = sql.NVarChar(4000);
exports.multiple = sql.NText;