Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
SQL

SQL: Optimize Performance with Stored Procedures

- 25.07.26 - ErcanOPAK

📦 Stored Procedures = Performance

Ad-hoc queries are inefficient. Stored procedures improve performance, security, and maintainability.

📝 Stored Procedure Examples

-- Simple Select
CREATE PROCEDURE GetUserById
    @UserId INT
AS
BEGIN
    SET NOCOUNT ON;
    SELECT * FROM Users WHERE Id = @UserId;
END

-- With Parameters
CREATE PROCEDURE GetOrdersByDate
    @StartDate DATE,
    @EndDate DATE
AS
BEGIN
    SELECT o.*, u.Name AS CustomerName
    FROM Orders o
    JOIN Users u ON o.UserId = u.Id
    WHERE o.OrderDate BETWEEN @StartDate AND @EndDate
    ORDER BY o.OrderDate DESC;
END

-- With Output Parameter
CREATE PROCEDURE CreateOrder
    @UserId INT,
    @Total DECIMAL(10,2),
    @OrderId INT OUTPUT
AS
BEGIN
    INSERT INTO Orders (UserId, Total, OrderDate)
    VALUES (@UserId, @Total, GETDATE());
    SET @OrderId = SCOPE_IDENTITY();
END

-- With Error Handling
CREATE PROCEDURE UpdateInventory
    @ProductId INT,
    @Quantity INT
AS
BEGIN
    BEGIN TRY
        BEGIN TRANSACTION;
        
        UPDATE Products 
        SET StockQuantity = StockQuantity - @Quantity
        WHERE Id = @ProductId;
        
        IF @@ROWCOUNT = 0
        BEGIN
            RAISERROR('Product not found', 16, 1);
            ROLLBACK;
            RETURN;
        END
        
        COMMIT;
    END TRY
    BEGIN CATCH
        ROLLBACK;
        THROW;
    END CATCH
END

🎯 Advanced Patterns

-- Dynamic Search
CREATE PROCEDURE SearchProducts
    @Name NVARCHAR(100) = NULL,
    @CategoryId INT = NULL,
    @MinPrice DECIMAL(10,2) = NULL,
    @MaxPrice DECIMAL(10,2) = NULL
AS
BEGIN
    SELECT * FROM Products
    WHERE (@Name IS NULL OR Name LIKE '%' + @Name + '%')
        AND (@CategoryId IS NULL OR CategoryId = @CategoryId)
        AND (@MinPrice IS NULL OR Price >= @MinPrice)
        AND (@MaxPrice IS NULL OR Price <= @MaxPrice);
END

-- Pagination
CREATE PROCEDURE GetProductsPaged
    @PageNumber INT,
    @PageSize INT,
    @SortColumn NVARCHAR(50) = 'Id',
    @SortDirection NVARCHAR(4) = 'ASC'
AS
BEGIN
    DECLARE @Sql NVARCHAR(MAX);
    SET @Sql = N'
        SELECT * FROM Products
        ORDER BY ' + QUOTENAME(@SortColumn) + ' ' + @SortDirection + '
        OFFSET @Offset ROWS
        FETCH NEXT @PageSize ROWS ONLY'
    
    EXEC sp_executesql @Sql,
        N'@Offset INT, @PageSize INT',
        @Offset = (@PageNumber - 1) * @PageSize,
        @PageSize = @PageSize;
END

-- Bulk Operations
CREATE TYPE IdList AS TABLE (Id INT);

CREATE PROCEDURE DeleteUsersBulk
    @UserIds IdList READONLY
AS
BEGIN
    DELETE FROM Users
    WHERE Id IN (SELECT Id FROM @UserIds);
END

💡 Stored Procedure Tips

  • Use SET NOCOUNT ON for performance
  • Use parameterized queries for security
  • Handle errors with TRY/CATCH
  • Use transactions for data integrity
  • Monitor execution plans

Stored procedures are the workhorses of enterprise databases. They deliver performance and security.

— Database Developer

Related posts:

SQL “Blocking Sessions” — The Hidden Killer: Orphaned Transactions

SQL “Blocking Sessions” — The Hidden Killer: Orphaned Transactions

SQL: Use COALESCE to Handle NULL Values

SQL: Use COALESCE to Handle NULL Values

SQL: Use EXISTS Instead of IN for Better Performance

SQL: Use EXISTS Instead of IN for Better Performance

Views: 14

Post navigation

.NET Core: Structured Logging with Serilog
C#: Use Collection Initializers for Clean Code

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (481)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com