How to use the VarChar function from mssql

Find comprehensive JavaScript mssql.VarChar code examples handpicked from public code repositorys.

mssql.VarChar is a data type in the mssql library that represents a variable-length string in SQL Server.

192
193
194
195
196
197
198
199
200
201
    
    // 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 => {
fork icon463
star icon1
watch icon2

+ 3 other calls in file

58
59
60
61
62
63
64
65
66
67
    
// Stored Procedure
    
var request = new sql.Request(connection);
request.input('input_parameter', sql.Int, 10);
request.output('output_parameter', sql.VarChar(50));
request.execute('procedure_name', function(err, recordsets, returnValue) {
    // ... error checks
    
    console.dir(recordsets);
fork icon463
star icon0
watch icon78

+ 59 other calls in file

How does mssql.VarChar work?

mssql.VarChar is a data type provided by the mssql library that represents a variable-length string in SQL Server. To use mssql.VarChar, you can declare a column in a SQL Server table or a parameter in a stored procedure with the VarChar data type, which indicates that the column or parameter can contain a string of variable length. For example, to create a table with a VarChar column in SQL Server, you could use the following SQL code: sql Copy code {{{{{{{ class="!whitespace-pre hljs language-sql">CREATE TABLE MyTable ( MyColumn VARCHAR(50) ); In this example, the MyColumn column is declared with the VarChar data type and a length of 50, which means it can contain a string of up to 50 characters. In the mssql library, you can use the VarChar data type to define parameters when executing a query or a stored procedure. For example: javascript Copy code {{{{{{{ const sql = require('mssql'); const pool = new sql.ConnectionPool(config); await pool.connect(); const result = await pool.request() .input('myParam', sql.VarChar, 'Hello, world!') .query('SELECT * FROM MyTable WHERE MyColumn = @myParam'); console.log(result); In this example, we use the sql.VarChar data type to define a parameter in a query executed by the mssql library. The VarChar data type is used to indicate that the parameter should be treated as a string of variable length. We pass in a value of 'Hello, world!' as the parameter value. When the query is executed, the mssql library automatically maps the VarChar data type to the appropriate SQL Server data type (varchar in this case) and passes the value to the server. This example demonstrates how you can use mssql.VarChar to define string parameters when executing SQL queries or stored procedures in the mssql library.

78
79
80
81
82
83
84
85
86
var typeName = SqlHelperMssql.typeName(fieldType);

if (typeName == 'text') return mssql.NVarChar;
else if (typeName == 'integer') return mssql.Int;
else if (typeName == 'decimal') return mssql.Float; //TODO - use decimal?
else if (typeName == 'timestamp') return mssql.VarChar(256); //TODO - use real js dates?
else if (typeName == 'date') return mssql.VarChar(256); //TODO - use real js dates?
else if (typeName == 'float') return mssql.Float;
else if (typeName == 'boolean') return mssql.Bit;
fork icon0
star icon2
watch icon3

+ 43 other calls in file

30
31
32
33
34
35
36
37
38

public getClientsByFilter(filter: string) : Promise<any>
{
    return sql.connect(sqlConfig).then((pool:any) => {
        return pool.request()
            .input("searchcriteria", sql.VarChar(40), filter)
            .execute("getFilteredClients")
    });
}
fork icon20
star icon11
watch icon2

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const sql = require("mssql");

const config = {
  user: "myUsername",
  password: "myPassword",
  server: "localhost",
  database: "myDatabase",
};

async function getDataByName(name) {
  const pool = await sql.connect(config);
  const result = await pool
    .request()
    .input("name", sql.VarChar(50), name)
    .query("SELECT * FROM MyTable WHERE Name = @name");

  console.log(result.recordset);
}

getDataByName("John");

In this example, we define a getDataByName function that retrieves data from a SQL Server database by name. We first establish a connection to the database using the sql.connect function and the connection configuration. We then use the pool.request function to create a new request object and define a parameter using the sql.VarChar data type. The VarChar data type is used to indicate that the name parameter should be treated as a string of variable length with a maximum length of 50 characters. We pass in the name argument as the parameter value. Finally, we execute a SQL query that selects data from a table based on the value of the Name column, using the @name parameter to filter the results. When the query is executed, the mssql library automatically maps the sql.VarChar data type to the appropriate SQL Server data type (varchar in this case) and passes the value to the server. This example demonstrates how you can use mssql.VarChar to define string parameters when executing SQL queries or stored procedures in the mssql library.

68
69
70
71
72
73
74
75
76
77
router.post('/many', async (req, res) => {
    try {
        await pool.connect();
        const employeesTable = new mssql.Table();

        employeesTable.columns.add('Code', mssql.VarChar(50));
        employeesTable.columns.add('Name', mssql.VarChar(50));
        employeesTable.columns.add('Job', mssql.VarChar(50));
        employeesTable.columns.add('Salary', mssql.Int);
        employeesTable.columns.add('Department', mssql.VarChar(50));
fork icon7
star icon10
watch icon2

+ 7 other calls in file

115
116
117
118
119
120
121
122
123
124

getVehicleLocationEndpoint: async (req, res) => {
  const tripId = req.body.trips[0]

  const sqlRequest = connection.get().request()
  sqlRequest.input('trip_id', sql.VarChar(50), tripId)
  try {
    const result = await sqlRequest.query(
      `
    SELECT TOP 1
fork icon7
star icon0
watch icon2

+ 7 other calls in file

17
18
19
20
21
22
23
24
25
  'GROUP BY DATEPART(mm, t.Date), p.Name, t.ProjectId ' +
  'ORDER BY CalendarMonth, Name ';

const params = Array<SqlParameter>();
params.push(new SqlParameter('Year', mssql.Int, year));
params.push(new SqlParameter('State', mssql.VarChar(50), StatusConstants.ACTIVE));

const manager = new SqlManager(environment.db);
const result = await manager.executeQuery(sql, params);
fork icon0
star icon4
watch icon4

+ 5 other calls in file

74
75
76
77
78
79
80
81
82
83
    if (isSysAdmin !== true) {
      sql += ' AND (f.isPublic = 1 ' +
        ' OR fu.flickId IS NOT NULL ' +
        ' OR f.userId = @userId ) ';
    }
request.input('id', mssql.VarChar(36), id);
request.input('userId', mssql.UniqueIdentifier, userId);
request.query(sql, function (err, recordset) {
    if (statsD) {
        statsD.timing('flick.doGetFlickById', dbStartTime);
fork icon1
star icon3
watch icon2

40
41
42
43
44
45
46
47
48
}

async create(project: ProjectDataInfo) {
  const sql = 'INSERT INTO Projects (Id,Name,Description,State) VALUES (@Id,@Name,@Description,@State)';
  const params = Array<SqlParameter>();
  params.push(new SqlParameter('Id', mssql.VarChar(36), uuidv1()));
  params.push(new SqlParameter('Name', mssql.VarChar(50), project.name));
  params.push(new SqlParameter('Description', mssql.VarChar(500), project.description));
  params.push(new SqlParameter('State', mssql.VarChar(50), StatusConstants.ACTIVE));
fork icon0
star icon4
watch icon4

+ 17 other calls in file

92
93
94
95
96
97
98
99
100
101
},
getVehicleLocationEndpoint: function(req, res) {
  const trip_id = req.body.trips[0]

  const sqlRequest = connection.get().request()
  sqlRequest.input('trip_id', sql.VarChar(50), trip_id)
  sqlRequest.query(`
    SELECT TOP 1
      route_short_name, direction_id
    FROM trips 
fork icon7
star icon0
watch icon1

+ 11 other calls in file

170
171
172
173
174
175
176
177
178
179
if (val) {
  return val;
}
await this.createPool();
const request = await this.pool.request();
request.input('Email', sql.VarChar(200), email);
const recordSet = await request.execute('CheckUser');
if (recordSet) {
  this.myCache.set(cacheKey, recordSet.recordset[0].Result === 1);
  return recordSet.recordset[0].Result === 1;
fork icon4
star icon0
watch icon2

+ 11 other calls in file

44
45
46
47
48
49
50
51
52
53
let conn = await db.connect()
let ps = new sql.PreparedStatement(conn)
try {
    //await ps.prepare("INSERT INTO LectureHistory (name, dateStr, timestamp) VALUES ('曹东江的自我修养','2019-04-05',0)")

    ps.input('cardnum', sql.VarChar(9))
    ps.input('location', sql.NVarChar(50))
    ps.input('name', sql.NVarChar(50))
    ps.input('dateStr', sql.NVarChar(50))
    ps.input('timestamp', sql.Numeric)
fork icon0
star icon3
watch icon7

6
7
8
9
10
11
12
13
14
15
    return {
        type: mssql.Numeric,
        value
    };
}else if(typeof value==='object' && value.value){
    if(!value.type) value.type = mssql.VarChar;
    return value;
}else{
    return {
        type: mssql.VarChar,
fork icon1
star icon0
watch icon2

+ 3 other calls in file

115
116
117
118
119
120
121
122
123

let pool = await sql.connect(config.db); 

try {
  let dbresults = await pool.request()
  .input('keywords', sql.VarChar(150), keywords)
  .execute('SEARCH_CODES');

  results.codes = dbresults.recordset;
fork icon1
star icon0
watch icon2

45
46
47
48
49
50
51
52
53
54
const params = Array<SqlParameter>();
params.push(new SqlParameter('Id', mssql.VarChar(36), uuidv1()));

params.push(new SqlParameter('Date', mssql.Date, bill.date));
params.push(new SqlParameter('Nro', mssql.VarChar(36), bill.nro));
params.push(new SqlParameter('Client', mssql.VarChar(50), bill.client));
params.push(new SqlParameter('Currency', mssql.VarChar(50), bill.currency));
params.push(new SqlParameter('Subtotal', mssql.Decimal(18, 2), bill.subtotal));
params.push(new SqlParameter('Taxes', mssql.Decimal(18, 2), bill.taxes));
params.push(new SqlParameter('Total', mssql.Decimal(18, 2), bill.total));
fork icon0
star icon4
watch icon4

+ 25 other calls in file

30
31
32
33
34
35
36
37
38
const Bit = sql.Bit;
const TinyInt = sql.TinyInt;
const SmallInt = sql.SmallInt;
const Int = sql.Int;
const BigInt = sql.BigInt;
const Varchar = (length) => sql.VarChar(length);
const NVarchar = (length) => sql.NVarChar(length);
const Decimal = (digits, precision) => sql.Decimal(digits, precision);
const Table = () => new sql.Table();
fork icon0
star icon4
watch icon2

145
146
147
148
149
150
151
152
153
if (lineData.agencyFilter) {
  const agencyId = lineData.agencyFilter(lineId)
  if (agencyId !== null) {
    lineId = lineId.replace(agencyId, '')
    agency = 'and routes.agency_id = @agency_id'
    sqlRequest.input('agency_id', sql.VarChar(50), agencyId)
  }
}
sqlRequest.input('route_short_name', sql.VarChar(50), lineId)
fork icon7
star icon0
watch icon1

+ 3 other calls in file

77
78
79
80
81
82
83
84
85
86
// create a generic temp table with same number of cols as target.
const table = new sql.Table(tempTablename);
table.create = true;

for (let x = 0; x < numCols; x += 1) {
  table.columns.add(`col${x}`, sql.VarChar(8000), { nullable: true });
}
tableArr.forEach((record) => {
  table.rows.add(...record);
});
fork icon1
star icon1
watch icon0

16
17
18
19
20
21
22
23
24
25
if (err)
    console.log(err);

var request = new sql.Request();
request.input('UserID', sql.VarChar(50), req.body.userid)
    .input('PassWord', sql.VarChar(50), req.body.passwd)
    .query('select * from UserList where UserID = @UserID AND PassWord = @PassWord', function (err, recordset) {

        if (err) {
            console.log(err)
fork icon1
star icon1
watch icon2

+ 3 other calls in file

2
3
4
5
6
7
8
9
10
11
12


async function getPartnerNameById(partnerId){
    try{
        let pool = await sql.connect(config);
        let flights = await pool.request()
            .input('MaHangBay', sql.VarChar(10), partnerId)
            .query("Select TenHangBay From HangBay HB Where HB.MaHangBay = @MaHangBay");
        return flights.recordsets;
    }
    catch(error){
fork icon0
star icon1
watch icon0

+ 3 other calls in file