Tuesday, 4 March 2025

Optional Column Updates with T-SQL Stored Procedures

In many cases, when working with databases, you might need to update specific columns in a table. However, depending on your requirements, not all fields may need to be updated at once. This is particularly relevant when handling bulk updates, where only certain columns require modification while others remain unchanged.

A common problem is managing multiple stored procedures for different combinations of updated fields. Instead of creating a separate procedure for each variation, a more flexible solution involves using optional parameters with the COALESCE function in SQL Server. This way, the stored procedure can update only the fields that are provided, while leaving the rest untouched.

Problem Overview

Suppose you have a table Product with columns like PartNumber, Description, and Comments, and you need to update one or more of these columns based on certain conditions. Instead of writing separate stored procedures for each update combination, we can create a single procedure that accepts optional parameters and uses COALESCE to handle the updates flexibly.

Solution: Optional Update with COALESCE

Here’s an example of how we can use COALESCE with typed null values to create a stored procedure that updates the Description and Comments columns only when new values are provided. If a parameter is passed as NULL, the column will remain unchanged.

Example Code:

Step 1: Create the Demo Table

First, let’s create a simple Product table to demonstrate the concept.

CREATE TABLE [dbo].[Product](
    ULL
) ON [Pp 2: Insertinsert a sample record to work with.

```sql
INSERT INTO [Product] VALUES (N'PART1', N'PART 1 Description', N'PART 1 Comment');
GO

Step 3: Create the Stored Procedure for Update

Now, let’s create the stored procedure spProduct_Update, which takes PartNumber, Description, and Comments as parameters. It uses COALESCE to conditionally update the columns.

CREATE PROCEDURE [dbo].[spProduct_Update]
    @PartNumber AS NVARCHAR(20),
    @Description AS NCHAR(20),
    @Comments AS NCHAR(20)
AS
BEGIN
    DECLARE @BEFORE AS NVARCHAR(200);
    DECLARE @AFTER AS NVARCHAR(200);

    -- Capture the state of the record before update
    SELECT @BEFORE = 'BEFORE: ' + [PartNumber] + '  |  ' + [Description] + '  |  ' + [Comments] 
    FROM [Product] 
    WHERE [PartNumber] = @PartNumber;

    -- Update the columns using COALESCE to check if new values are provided
    UPDATE [Product]
    SET 
        [Description] = COALESCE(@Description, [Description]),
        [Comments] = COALESCE(@Comments, [Comments])
    WHERE [PartNumber] = @PartNumber;

    -- Capture the state of the record after update
    SELECT @AFTER = 'AFTER: ' + [PartNumber] + '  |  ' + [Description] + '  |  ' + [Comments] 
    FROM [Product] 
    WHERE [PartNumber] = @PartNumber;

    -- Print before and after states for debugging
    PRINT @BEFORE;
    PRINT @AFTER;
END
GO

Step 4: Testing the Stored Procedure

Here are some examples of how to use this stored procedure:

  1. No Updates (both parameters are null)

    This will leave the record unchanged.

    EXEC spProduct_Update 'PART1', NULL, NULL;
    
  2. Update Description Only

    This will update the Description field but leave Comments unchanged.

    EXEC spProduct_Update 'PART1', 'PART 1 *** UPDATE DESCRIPTION ***', NULL;
    
  3. Update Comments Only

    This will update the Comments field but leave Description unchanged.

    EXEC spProduct_Update 'PART1', NULL, 'PART 1 *** UPDATE COMMENT ***';
    
  4. Update Both Description and Comments

    This will update both fields with new values.

    EXEC spProduct_Update 'PART1', '*** UPDATE BOTH ***', '*** UPDATE BOTH ***';
    

Step 5: Clean Up

After testing, you can drop the stored procedure and the demo table to clean up the environment.

DROP PROCEDURE [dbo].[spProduct_Update];
GO

DROP TABLE [dbo].[Product];
GO

Explanation of COALESCE Usage

The key concept here is the use of COALESCE. The COALESCE function returns the first non-null expression from its list of parameters. Here, we pass the value of the @Description and @Comments parameters as the first argument and the current column values as the second argument. If the passed parameter is NULL, the column will remain unchanged.

  • COALESCE(@Description, [Description]): If @Description is NULL, the current value of [Description] remains unchanged.
  • COALESCE(@Comments, [Comments]): Similarly, if @Comments is NULL, the current value of [Comments] remains unchanged.

Conclusion

By using COALESCE with typed null values, we create a flexible stored procedure that can handle optional updates for specific columns. This reduces the need for multiple stored procedures for each combination of updates and simplifies the maintenance of the code.

Prevent new Tab/Duplicate Tab open or Managing Multiple Tabs and Sessions in JavaScript: A Practical Approach

 

Managing Multiple Tabs and Sessions in JavaScript: A Practical Approach

In modern web applications, users often open multiple tabs to interact with the same website. This can lead to various issues, such as duplicated sessions or conflicting states. A common problem is ensuring that only one active session exists per user at a time. To handle this, we can use JavaScript to track sessions and manage behaviors across multiple tabs. In this post, we’ll walk through a solution for managing sessions across multiple tabs and handling scenarios such as preventing multiple sessions or ensuring the user is logged out properly.

The Challenge:

When a user opens multiple tabs of the same application, there may be conflicts between tabs, such as:

  1. Session Duplication: The user might unintentionally create multiple sessions across tabs.
  2. State Inconsistency: Actions in one tab may not be reflected across other tabs.
  3. Tab Closure: The session should clean up after itself when the user closes the tab.

The Solution: TabManage Function

We can address these challenges using JavaScript and the localStorage API to track session states across tabs. Below is a detailed breakdown of how the TabManage function works to manage sessions:

function TabManage(sessionId) {
    console.log("Referrer:", document.referrer);

    // Check if there is a referrer (useful for detecting direct access)
    if (!document.referrer) {
        console.log("No referer. Redirecting to login.");
        var url = "/Login/Logout";
        window.location.href = url;
        return;
    }

    // Check for existing session across tabs using localStorage
    if (!localStorage.getItem('sessionCreated')) {
        // First tab visit in the session
        localStorage.setItem('sessionCreated', Date.now());
        window.name = "session_tab"; // Mark this tab as the first tab
        console.log("Session created:", localStorage.getItem('sessionCreated'));
    } else {
        // If session is already created, check if another tab is open
        console.log("Existing session:", localStorage.getItem('sessionCreated'), "Window Name:", window.name);
        if (window.name !== "session_tab") {
            // This is a duplicate tab, redirecting
            window.name = "duplicate_tab"; // Mark the new tab
            var url = "/Login/Logout";
            window.location.href = url;
        }
    }

    // Handle tab closure to clean up localStorage if all tabs are closed
    window.addEventListener('beforeunload', function () {
        if (window.name === "session_tab") {
            localStorage.removeItem('sessionCreated'); // Clean up session when the original tab is closed
        }
    });
}

Key Concepts and Functionality:

  1. Referrer Check:

    • The document.referrer checks if the user navigated from another page. If there is no referrer, indicating that the user may have landed directly on the page, they are redirected to the login page.
  2. Session Tracking with localStorage:

    • The localStorage API is used to store a session marker (sessionCreated). If this is the first tab, it sets this item and assigns the window.name to "session_tab", marking it as the primary session tab.
    • If the sessionCreated item already exists, this indicates that the user has opened another tab. The function checks whether the new tab is the first session tab or a duplicate, redirecting duplicate tabs to the login page.
  3. Preventing Multiple Active Sessions:

    • The function ensures that only one session is allowed at a time. If another tab tries to open while the session is already active, it redirects the user to the login page to avoid session conflicts.
  4. Clean-up on Tab Closure:

    • The beforeunload event listener ensures that when the first tab is closed, the session data in localStorage is removed, making sure that all tabs are effectively logged out once the original tab is closed.

Why Is This Important?

  1. User Experience: It ensures that users do not end up with conflicting sessions when they open multiple tabs, reducing potential errors and confusion.
  2. Security: It helps to avoid situations where a user might unknowingly remain logged in on multiple tabs, improving overall security by preventing multiple active sessions.
  3. Consistency: The session handling ensures that actions taken in one tab are reflected consistently across all open tabs.

Conclusion:

The TabManage function provides a simple yet effective solution for managing user sessions across multiple tabs in a web application. By using localStorage and window.name, this approach prevents session duplication and ensures that the application maintains a consistent state. This method is particularly useful in web applications where user sessions must be isolated and controlled across multiple tabs, leading to a smoother and more secure experience.

By implementing such solutions, developers can enhance both the user experience and security of their applications.