How to call/fetch data from a stored procedure in SQL Server using TypeScript and Node.js

How to call/fetch data from a stored procedure in SQL Server using TypeScript and Node.js

A comprehensive guide to invoking SQL Server stored procedures from Node.js using TypeScript, featuring connection pooling, DTOs, TVPs, and streaming.

In modern enterprise architectures, ORMs like TypeORM or Prisma dominate Node.js backend development. However, high-throughput financial systems, legacy database integrations, and data-intensive applications often rely on SQL Server Stored Procedures.

Stored procedures provide centralized execution plans, fine-grained security boundaries, encapsulated transaction logic, and reduced network payload overhead. Yet, integrating T-SQL stored procedures into a strongly typed TypeScript backend introduces specific operational challenges: managing asynchronous connection pools, handling dynamic input/output parameters, mapping multiple result sets to type-safe Data Transfer Objects (DTOs), and streaming large datasets without exhausting Node.js heap memory.

This guide explores an enterprise-grade pattern for integrating SQL Server stored procedures into Node.js applications using TypeScript and the native node-mssql driver.


Architectural Blueprint

Before writing code, let’s examine the architectural boundaries. The application layer must isolate SQL Server interaction details behind data repositories. The Node.js runtime interacts with Microsoft SQL Server through a managed connection pool, translating strongly typed domain models into database-compatible types.

+-----------------------------------------------------------------------+
|                         Node.js Application                           |
|                                                                       |
|  +------------------------+        +-------------------------------+  |
|  |  Controller / Service  | -----> | CustomerRepository Interface  |  |
|  +------------------------+        +-------------------------------+  |
|                                                    |                  |
|                                                    v                  |
|                                    +-------------------------------+  |
|                                    | SqlServerCustomerRepository   |  |
|                                    +-------------------------------+  |
|                                                    |                  |
|                                                    v                  |
|                                    +-------------------------------+  |
|                                    |    Connection Pool Singleton  |  |
|                                    +-------------------------------+  |
+----------------------------------------------------+------------------+
                                                     |
                                            TDS Protocol (Port 1433)
                                                     |
                                                     v
+-----------------------------------------------------------------------+
|                          Microsoft SQL Server                         |
|                                                                       |
|   +---------------------------------------------------------------+   |
|   | Stored Procedure: dbo.usp_GetCustomerOrderSummary             |   |
|   |  - Execution Plan Cache                                       |   |
|   |  - Output Parameters & TVPs                                   |   |
|   |  - Multiple Recordsets                                        |   |
|   +---------------------------------------------------------------+   |
+-----------------------------------------------------------------------+

Database Baseline: Complex T-SQL Stored Procedure

To demonstrate advanced execution patterns—including input parameters, output parameters, multiple recordsets, and Table-Valued Parameters (TVPs)—we will use the following SQL Server setup.

CREATE TYPE dbo.UDT_OrderIdList AS TABLE (
    OrderId INT NOT NULL
);
GO

CREATE OR ALTER PROCEDURE dbo.usp_GetCustomerOrderSummary
    @CustomerId INT,
    @StartDate DATETIME2,
    @EndDate DATETIME2,
    @FilterOrders dbo.UDT_OrderIdList READONLY,
    @TotalOrders INT OUTPUT,
    @IsVIPAccount BIT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    -- Validate Inputs
    IF @CustomerId <= 0
    BEGIN
        RAISERROR('Invalid CustomerId provided.', 16, 1);
        RETURN;
    END

    -- Populate Output Parameters
    SELECT @TotalOrders = COUNT(*)
    FROM dbo.Orders o
    INNER JOIN @FilterOrders f ON o.OrderId = f.OrderId
    WHERE o.CustomerId = @CustomerId
      AND o.CreatedDate BETWEEN @StartDate AND @EndDate;

    SELECT @IsVIPAccount = CASE WHEN Tier = 'VIP' THEN 1 ELSE 0 END
    FROM dbo.Customers
    WHERE CustomerId = @CustomerId;

    -- Result Set 1: Summary Statistics
    SELECT 
        o.CustomerId,
        SUM(o.TotalAmount) AS AggregateSpend,
        AVG(o.TotalAmount) AS AverageOrderValue
    FROM dbo.Orders o
    INNER JOIN @FilterOrders f ON o.OrderId = f.OrderId
    WHERE o.CustomerId = @CustomerId
      AND o.CreatedDate BETWEEN @StartDate AND @EndDate
    GROUP BY o.CustomerId;

    -- Result Set 2: Detailed Line Items
    SELECT 
        o.OrderId,
        o.CreatedDate,
        o.TotalAmount,
        o.OrderStatus
    FROM dbo.Orders o
    INNER JOIN @FilterOrders f ON o.OrderId = f.OrderId
    WHERE o.CustomerId = @CustomerId
      AND o.CreatedDate BETWEEN @StartDate AND @EndDate
    ORDER BY o.CreatedDate DESC;
END;
GO

Infrastructure: Connection Pool & Driver Abstraction

In Node.js, standard database connections should rarely be opened and closed per request. Doing so introduces substantial latency through handshakes, authentication, and connection allocation inside SQL Server. We use mssql (which wraps tedious) to implement a thread-safe Singleton Connection Pool.

Driver Installation

npm install mssql
npm install --save-dev @types/mssql

Connection Pool Singleton Manager

// src/infrastructure/database/DatabaseConnectionFactory.ts
import sql from 'mssql';

export interface DatabaseConfig {
  user: string;
  password: string;
  server: string;
  database: string;
  port: number;
  poolMin: number;
  poolMax: number;
  idleTimeoutMillis: number;
}

export class DatabaseConnectionFactory {
  private static instance: sql.ConnectionPool | null = null;
  private static isConnecting = false;

  private constructor() {}

  public static async getPool(config: DatabaseConfig): Promise<sql.ConnectionPool> {
    if (this.instance && this.instance.connected) {
      return this.instance;
    }

    if (this.isConnecting) {
      return new Promise((resolve, reject) => {
        const interval = setInterval(() => {
          if (this.instance && this.instance.connected) {
            clearInterval(interval);
            resolve(this.instance);
          }
        }, 50);
        
        setTimeout(() => {
          clearInterval(interval);
          reject(new Error('Connection pool initialization timeout.'));
        }, 10000);
      });
    }

    this.isConnecting = true;

    try {
      const sqlConfig: sql.config = {
        user: config.user,
        password: config.password,
        server: config.server,
        database: config.database,
        port: config.port,
        options: {
          encrypt: true, // Required for Azure SQL; recommended for enterprise security
          trustServerCertificate: false, // Set to true only in local dev
          enableArithAbort: true,
        },
        pool: {
          min: config.poolMin,
          max: config.poolMax,
          idleTimeoutMillis: config.idleTimeoutMillis,
        },
      };

      const pool = new sql.ConnectionPool(sqlConfig);
      
      pool.on('error', (err) => {
        console.error('[SQL Pool Error]:', err);
      });

      this.instance = await pool.connect();
      console.info('[SQL Pool]: Connection pool successfully established.');
      return this.instance;
    } catch (error) {
      console.error('[SQL Pool Error]: Failed to create connection pool.', error);
      throw error;
    } finally {
      this.isConnecting = false;
    }
  }

  public static async closePool(): Promise<void> {
    if (this.instance) {
      await this.instance.close();
      this.instance = null;
      console.info('[SQL Pool]: Connection pool closed.');
    }
  }
}

Domain Modeling: DTOs & Type Definitions

Enterprise applications require strict operational contracts. Define interfaces for:

  1. Procedure input parameters.
  2. Result Set structures (each distinct query output).
  3. Procedure output parameters.
  4. Final compiled execution response.
// src/domain/dtos/CustomerOrderSummaryDtos.ts

export interface GetCustomerOrderSummaryInput {
  customerId: number;
  startDate: Date;
  endDate: Date;
  filterOrderIds: number[];
}

export interface SpendSummaryRecordset {
  CustomerId: number;
  AggregateSpend: number;
  AverageOrderValue: number;
}

export interface OrderDetailRecordset {
  OrderId: number;
  CreatedDate: Date;
  TotalAmount: number;
  OrderStatus: string;
}

export interface GetCustomerOrderSummaryOutputs {
  totalOrders: number;
  isVIPAccount: boolean;
}

export interface GetCustomerOrderSummaryResponse {
  outputs: GetCustomerOrderSummaryOutputs;
  spendSummary: SpendSummaryRecordset | null;
  orderDetails: OrderDetailRecordset[];
}

The Data Access Layer: Executing Stored Procedures

We encapsulate procedure call mechanics inside a concrete repository implementation. This layer handles mapping JavaScript types to SQL Server types, constructing Table-Valued Parameters, executing the request, and parsing results.

// src/infrastructure/repositories/SqlServerCustomerRepository.ts
import sql from 'mssql';
import { DatabaseConnectionFactory, DatabaseConfig } from '../database/DatabaseConnectionFactory';
import {
  GetCustomerOrderSummaryInput,
  GetCustomerOrderSummaryResponse,
  SpendSummaryRecordset,
  OrderDetailRecordset,
} from '../../domain/dtos/CustomerOrderSummaryDtos';

export class SqlServerCustomerRepository {
  constructor(private readonly dbConfig: DatabaseConfig) {}

  public async getCustomerOrderSummary(
    input: GetCustomerOrderSummaryInput
  ): Promise<GetCustomerOrderSummaryResponse> {
    const pool = await DatabaseConnectionFactory.getPool(this.dbConfig);
    const request = pool.request();

    // 1. Primitive Input Parameters
    request.input('CustomerId', sql.Int, input.customerId);
    request.input('StartDate', sql.DateTime2, input.startDate);
    request.input('EndDate', sql.DateTime2, input.endDate);

    // 2. Table-Valued Parameter (TVP) Binding
    const orderIdTable = new sql.Table('dbo.UDT_OrderIdList');
    orderIdTable.columns.add('OrderId', sql.Int, { nullable: false });
    
    for (const orderId of input.filterOrderIds) {
      orderIdTable.rows.add(orderId);
    }
    
    request.input('FilterOrders', orderIdTable);

    // 3. Declare Output Parameters
    request.output('TotalOrders', sql.Int);
    request.output('IsVIPAccount', sql.Bit);

    try {
      // 4. Execute the Stored Procedure
      const result = await request.execute('dbo.usp_GetCustomerOrderSummary');

      // 5. Extract Output Parameters safely
      const totalOrders = result.output.TotalOrders as number;
      const isVIPAccount = Boolean(result.output.IsVIPAccount);

      // 6. Map Multiple Recordsets
      // result.recordsets is an array of record arrays representing SELECT statements in T-SQL
      const spendSummarySet = result.recordsets[0] as SpendSummaryRecordset[];
      const orderDetailsSet = result.recordsets[1] as OrderDetailRecordset[];

      return {
        outputs: {
          totalOrders,
          isVIPAccount,
        },
        spendSummary: spendSummarySet.length > 0 ? spendSummarySet[0] : null,
        orderDetails: orderDetailsSet,
      };
    } catch (error) {
      this.handleSqlError('dbo.usp_GetCustomerOrderSummary', error);
      throw error;
    }
  }

  private handleSqlError(procedureName: string, error: unknown): void {
    if (error instanceof sql.RequestError) {
      console.error(`[SQL Error] Procedure ${procedureName} failed:`, {
        code: error.code,
        number: error.number,
        state: error.state,
        class: error.class,
        message: error.message,
      });
      return;
    }
    console.error(`[Unexpected Error] Procedure ${procedureName} execution failed:`, error);
  }
}

Streaming Large Result Sets for Memory Efficiency

When executing a stored procedure that returns hundreds of thousands of rows, reading the entire payload into V8 heap memory via request.execute() can trigger garbage collection pauses or ERR_STRING_TOO_LONG / Out of Memory exceptions.

node-mssql supports event-driven streaming to process rows as they arrive across the TDS stream.

// src/infrastructure/repositories/SqlServerStreamingRepository.ts
import sql from 'mssql';
import { Readable } from 'stream';
import { DatabaseConnectionFactory, DatabaseConfig } from '../database/DatabaseConnectionFactory';
import { OrderDetailRecordset } from '../../domain/dtos/CustomerOrderSummaryDtos';

export class SqlServerStreamingRepository {
  constructor(private readonly dbConfig: DatabaseConfig) {}

  /**
   * Streams stored procedure rows directly via a Node.js Readable Stream.
   */
  public async streamLargeOrderExport(customerId: number): Promise<Readable> {
    const pool = await DatabaseConnectionFactory.getPool(this.dbConfig);
    const request = pool.request();

    // Enable stream mode on the request object BEFORE executing
    request.stream = true;

    request.input('CustomerId', sql.Int, customerId);

    const passThroughStream = new Readable({
      objectMode: true,
      read() {}, // No-op, pushed driven by node-mssql events
    });

    // Execute triggers execution; records emit via events rather than returning in a promise array
    request.execute('dbo.usp_ExportHistoricalCustomerOrders');

    // Emitted when a new recordset starts (in case procedure returns multiple)
    request.on('recordset', (columns) => {
      console.debug('[Stream Manager] New Recordset initialized with columns:', Object.keys(columns));
    });

    // Emitted per individual row read off TDS buffer
    request.on('row', (row: OrderDetailRecordset) => {
      const keepsFlowing = passThroughStream.push(row);
      if (!keepsFlowing) {
        // Pause underlying database stream if downstream consumer backpressure is triggered
        request.pause();
      }
    });

    // Handle backpressure resumption
    passThroughStream.on('drain', () => {
      request.resume();
    });

    // Emitted on error
    request.on('error', (err) => {
      console.error('[Stream Error]:', err);
      passThroughStream.destroy(err);
    });

    // Emitted when TDS stream fully completes
    request.on('done', (result) => {
      console.info(`[Stream Manager] Execution completed. Affected Rows: ${result.rowsAffected}`);
      passThroughStream.push(null); // End of stream
    });

    return passThroughStream;
  }
}

Error Handling & Transaction Management

Enterprise systems require robust error mapping and transactional integrity.

When stored procedures manage explicit transactions internally (BEGIN TRANSACTION ... COMMIT TRANSACTION), Node.js code needs to interpret RAISERROR or THROW statements correctly. When transaction boundaries need to be controlled from Node.js, explicit transaction contexts must be passed to the stored procedure execution.

Node.js-Driven Transaction Management

// src/infrastructure/services/OrderProcessingService.ts
import sql from 'mssql';
import { DatabaseConnectionFactory, DatabaseConfig } from '../database/DatabaseConnectionFactory';

export class OrderProcessingService {
  constructor(private readonly dbConfig: DatabaseConfig) {}

  public async processOrderTransaction(
    customerId: number,
    orderId: number
  ): Promise<void> {
    const pool = await DatabaseConnectionFactory.getPool(this.dbConfig);
    
    // Create isolated transaction object from pool instance
    const transaction = new sql.Transaction(pool);

    try {
      // Begin transaction lock
      await transaction.begin(sql.ISOLATION_LEVEL.READ_COMMITTED);

      // Bind request strictly to the transaction context, NOT the pool connection directly
      const request = new sql.Request(transaction);

      request.input('CustomerId', sql.Int, customerId);
      request.input('OrderId', sql.Int, orderId);

      // Execute stored procedures within the transactional scope
      await request.execute('dbo.usp_DeductCustomerBalance');
      await request.execute('dbo.usp_UpdateInventoryStock');

      // Commit changes to database engine
      await transaction.commit();
      console.info(`[Transaction] Processing succeeded for OrderId: ${orderId}`);
    } catch (error) {
      console.error(`[Transaction Failed] Rolling back operations for OrderId: ${orderId}`, error);
      
      // Rollback transaction if initialization succeeded
      if (transaction.options.connection) {
        await transaction.rollback();
      }
      throw error;
    }
  }
}

Type Mapping Reference Matrix

To avoid implicit conversion bugs, truncate data, or force slow parameter-coercion scans in SQL execution plans, map your TypeScript primitives to mssql data types precisely:

SQL Server Data Type mssql Driver Type Mapping TypeScript Type
INT / SMALLINT / TINYINT sql.Int / sql.SmallInt / sql.TinyInt number
BIGINT sql.BigInt string / bigint
DECIMAL(p,s) / NUMERIC sql.Decimal(p, s) / sql.Numeric(p, s) number
VARCHAR / NVARCHAR sql.VarChar(length) / sql.NVarChar(length) string
DATETIME2 sql.DateTime2 Date
BIT sql.Bit boolean
VARBINARY(MAX) / IMAGE sql.VarBinary(sql.MAX) Buffer
UNIQUEIDENTIFIER sql.UniqueIdentifier string
User-Defined Table Type new sql.Table('schema.TypeName') Array<Object>

Production Readiness Checklist

When deploying stored procedure integrations to production, verify the following operational controls:

  1. Explicit Parameter Data Types: Never omit parameter data types in request.input(). Relying on automatic driver inferencing can result in implicit T-SQL data type conversions (e.g., VARCHAR implicitly converted to NVARCHAR), causing database engine index scans instead of index seeks.
  2. Execution Plan Pollution: Pass static parameter lengths when working with dynamic string bounds (e.g., sql.VarChar(50) instead of unbounded string inferences). This maintains uniform execution plan caching on SQL Server.
  3. Pool Connection Sizing: Size pool.max according to your Node.js instance concurrency and database worker threads. $$\text{Max Pool Size} = \left(\frac{\text{Target Concurrent Requests}}{\text{Node.js Cluster Instances}}\right) + \text{Buffer}$$
  4. SET NOCOUNT ON: Ensure all target stored procedures include SET NOCOUNT ON;. Without this, SQL Server sends DONE_IN_PROC tokens after every DML statement, which can cause Node.js drivers to parse extraneous metadata packets as result sets.
  5. Drain Listener Setup: Always register error handlers on the global pool (pool.on('error')) to prevent unhandled promise rejections during dynamic network socket resets.

Conclusion

Combining Node.js and TypeScript with SQL Server Stored Procedures delivers high-performance, strongly typed enterprise applications. By abstracting pool instances, enforcing concrete interface definitions over recordsets, correctly handling Table-Valued Parameters, and using streams for large payloads, you ensure your application remains scalable and resilient under high production loads.