Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7979245
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T09:43:37+00:00 2026-06-04T09:43:37+00:00

This is a question for a SQL expert. I’m using SQL Server 2008 R2

  • 0

This is a question for a SQL expert. I’m using SQL Server 2008 R2

I have two relevant tables: Labs and LabUsers.

Users are assigned to Labs with no repetitions of an entire groups of any order.

The goal is to insert a @userName (for the example @user = "Paul") into LabUsers fulfilling all the following limitations:

  1. No more than @maxUsers in a group (for the example @maxUsers=4)

  2. No duplicates of complete groups (full labs). The order of the users in a group is not significant. [edited]

  3. If no existing Lab is allowed, create (INSERT) a new lab, then insert the row for @user, given no exceeding @maxLabs (for the example @maxLabs=5).

  4. Very important: There are many concurrent same requests from the server in a split of a second, which may interfere one to the other. Therefore, as soon as the command begins to execute, no other queries are allowed to execute until the end of this command.

  5. The query should return 0 in cases it cannot meet the above restrictions, and return the LabID of the inserted row.

  6. [EDITED] There are several Labs’ zones. The zones are independent. Each zone #labCount is bounded by the @maxLabs. The @maxLabs is equal for all zones, therefore the Total_maxLabs = @maxLabs x #zonesCount . For the example @zone=51 (later on @zone=52, 53 etc.). (The same LabUsers can use zones with no limitations. Zones do not ‘know’ about each other)

  7. LabID in LabUsers is a foreign key from Labs.

The example:

Here is the Labs table:

LabID   LabName     LabZone
-----   -------     -------
1       North       51  
2       North East  51
3       South West  51

And the LabUsers is:

LabUserID   LabUserName LabID
---------   ----------- -----
1           Diana       3
2           Julia       2
3           Paula       2
4           Romeo       1
5           Julia       3
6           Rose        2
7           Diana       1
8           Diana       2
9           Julia       1
10          Romeo       3
11          Paul        1

In the example the users are assigned like this:

LabID   LabName     LabZone LabUsers (ordered LTR a>z)
-----   -------     ------- --------
1       North       51      Diana•Julia•Paul•Romeo
2       North East  51      Diana•Julia•Paula•Rose
3       South West  51      Diana•Julia•Romeo
  • The insert should not be into LabID=1 or 2 because there are already 4 users in these labs.
  • The insert should not take place into LabID=3 due to creating duplicate with LabID=1.

Therefore, because the @maxLabs is not 3 (existing labs), it is necessary to insert a new row into Labs with the value LabZone=@zone=51.

The IDENTITY will set the LabID to 4 for the new row.

Now is the time to insert Paul into LabUsers with LabID just returned from inserting a new lab.

How to solve this problem?

What is the method to use in order to ensure that the command is executed as a whole with no interference?

The script to create the database is:

CREATE DATABASE [Allocation]
GO

USE [Allocation]
GO

CREATE TABLE [dbo].[LabUsers](
    [LabUserID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED ,
    [LabUserName] [nvarchar](50) NOT NULL,
    [LabID] [int] NOT NULL)
GO

SET IDENTITY_INSERT [dbo].[LabUsers] ON
INSERT [dbo].[LabUsers] ([LabUserID], [LabUserName], [LabID]) VALUES (1, N'Diana', 3)
INSERT [dbo].[LabUsers] ([LabUserID], [LabUserName], [LabID]) VALUES (2, N'Julia', 2)
INSERT [dbo].[LabUsers] ([LabUserID], [LabUserName], [LabID]) VALUES (3, N'Paula', 2)
INSERT [dbo].[LabUsers] ([LabUserID], [LabUserName], [LabID]) VALUES (4, N'Romeo', 1)
INSERT [dbo].[LabUsers] ([LabUserID], [LabUserName], [LabID]) VALUES (5, N'Julia', 3)
INSERT [dbo].[LabUsers] ([LabUserID], [LabUserName], [LabID]) VALUES (6, N'Rose', 2)
INSERT [dbo].[LabUsers] ([LabUserID], [LabUserName], [LabID]) VALUES (7, N'Diana', 1)
INSERT [dbo].[LabUsers] ([LabUserID], [LabUserName], [LabID]) VALUES (8, N'Diana', 2)
INSERT [dbo].[LabUsers] ([LabUserID], [LabUserName], [LabID]) VALUES (9, N'Julia', 1)
INSERT [dbo].[LabUsers] ([LabUserID], [LabUserName], [LabID]) VALUES (10, N'Romeo', 3)
INSERT [dbo].[LabUsers] ([LabUserID], [LabUserName], [LabID]) VALUES (11, N'Paul', 1)
SET IDENTITY_INSERT [dbo].[LabUsers] OFF

CREATE TABLE [dbo].[Labs](
    [LabID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED ,
    [LabName] [nvarchar](50) NULL,
    [LabZone] [int] NOT NULL)
GO

SET IDENTITY_INSERT [dbo].[Labs] ON
INSERT [dbo].[Labs] ([LabID], [LabName], [LabZone]) VALUES (1, N'North', 51)
INSERT [dbo].[Labs] ([LabID], [LabName], [LabZone]) VALUES (2, N'North East', 51)
INSERT [dbo].[Labs] ([LabID], [LabName], [LabZone]) VALUES (3, N'South West', 51)
SET IDENTITY_INSERT [dbo].[Labs] OFF
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T09:43:38+00:00Added an answer on June 4, 2026 at 9:43 am

    I piggy backed off dradu’s variables and implemented a similar but different solution. It does make the assumption that a new lab will be 1 more than the maximum available current lab. I also make the assumption a lab does NOT remove users.

    The goal of this solution is to see what the end result of insertion of the user would look like and run checks on it to see which end result is valid. The logic is as follows:

    1. Get available labs to insert into
      • Check to make sure user not in lab here
      • Check to make sure lab not full here
      • Include new lab possibility here as well
    2. Create a list of all lab users per lab sorted alphabetically if the lab will be full after the user is inserted
      • the new possible labs are flagged
    3. Compare the flagged lab lists vs the unflagged lab lists and choose the minimum labId that isn’t a duplicate of an existing full lab list
    4. Return LabId inserted into or 0 as output

    Given the starting data from the original question and execution in the order below:

    1. Insert @userName = “Paul”, @labZone = 51
      • Paul gets added to the newly created Lab 4
    2. Insert @userName = “Paul”, @labZone = 51
      • Paul gets added to the newly created Lab 5
    3. Insert @userName = “Paul”, @labZone = 51
      • No more new labs and no existing labs for Paul to go to so return 0
    4. Insert @userName = “Rose”, @labZone = 51
      • Rose gets added to the existing Lab 3
    5. Insert @userName = “Rose”, @labZone = 51
      • Rose gets added to the existing Lab 4
    6. Insert @userName = “Rose”, @labZone = 51
      • Rose gets added to the existing Lab 5

    A tablockx within the transaction on LabUsers should prevent concurrent transactions from causing havoc.

    Also, when debugging common table expressions, it helps to replace them with a temporary table so you can look at the results of each step along the way.

    BEGIN TRAN
    
    DECLARE @maxUsers INT
    DECLARE @maxLabs INT
    DECLARE @userName VARCHAR(50)
    DECLARE @labZone INT
    DECLARE @labID INT
    
    SET @maxUsers = 4
    SET @maxLabs = 5
    
    SET @userName = 'Paul'
    SET @labZone = 52
    SET @labID = NULL
    
    declare @currentLabCount int
    
    -- get current number of labs
    select @currentLabCount = count(*)
    from Labs l
    /*
    -- uncomment this if the max labs applies individual lab zones rather than across all lab zones
    where LabZone = @labZone
    */  
    
    ;with availableLabs as ( -- get available labs to insert into
        -- check existing labs for valid spots
        select
            lu.LabID
        ,   count(*) + 1 as LabUserCount -- need this to see when we're at max users
        from LabUsers lu with (tablockx) -- ensures blocking until this completes (serialization)
          inner join Labs l with (tablockx) -- might as well lock this too
            on l.LabId = lu.LabID
            and l.LabZone = @labZone -- check Lab Zone
        where not exists( -- make sure lab user isn't already in this lab
            select 1
            from LabUsers lu2
            where lu2.LabId = lu.LabId
            and lu2.LabUserName = @userName
        )
        group by lu.LabID
        having count(*) < @maxUsers -- make sure lab isn't full
        union all
        -- create new lab if not at limit
        select
            max(LabId) + 1 as LabId
        ,   1 as LabUserCount
        from Labs -- check all labs
        where @currentLabCount < @maxLabs -- don't bother checking new labs if going to exceed max allowable labs
    )
    -- only do this check if lab is going to be filled
    , dupeCheck as( -- generates a lab user list sorted alphabetically by lab user name per lab
        select
            y.LabId
        ,   max(y.newLabFlag) as newLabFlag -- if existing lab getting new lab user, then 1, if new lab with new lab user, then 1 else 0
        ,   replace(replace(replace(stuff( -- cool way to comma concatenate without looping/recursion taking advantage of "XML path"
                (
                    select
                        ',' + x.LabUserName + '' -- lab users
                    from (
                        select
                            LabId
                        ,   @userName as LabUserName 
                        from availableLabs -- the new user and his/her potential labs
                        union all
                        select
                            lu.LabId
                        ,   lu.LabUserName
                        from LabUsers lu -- the current lab users and the labs they belong to
                    ) x
                    where x.LabID = y.LabId -- make sure the LabId's match
                    and max(y.LabUserCount) = @maxUsers -- don't generate this list if lab is not full
                    order by x.LabUserName -- sorted alphabetically
                    for xml path('')
                ), 1, 1, ''
            )
            , '&lt;', '<'), '&gt;', '>'), '&amp;', '&') as LabUserList
        from (
            -- get list of old labs and flag them as such
            select
                lu.LabId
            ,   convert(tinyint,0) as newLabFlag
            ,   count(*) as LabUserCount -- need the current lab user count
            from LabUsers lu
            /*
                -- uncomment this if full labs can be duplicated across lab zones
                inner join Labs l
                    on l.LabId = lu.LabId
                    and l.LabZone = @labZone
            */
            group by lu.LabId
            union all
            -- get list of potential candidate labs for lab user and flag them as such
            select
                al.LabId
            ,   convert(tinyint,1) as newLabFlag
            ,   al.LabUserCount -- new lab user count if we were to insert the new user
            from availableLabs al
        ) y
        group by y.LabId
    )
    select
        @labID = min(dc.LabID)
    from dupeCheck dc
    where dc.newLabFlag = 1
    -- make sure the same list of users does not already exist at an existing lab
    and not exists(
        select 1
        from dupeCheck dupe
        where dupe.LabUserList = dc.LabUserList
        and dupe.newLabFlag = 0
    )
    
    -- insert new lab if doesn't exist
    insert into Labs(LabName, LabZone) -- always better to be clearer
    select
        'New Lab' as LabName
    ,   @labZone as LabZone
    where @currentLabCount < @maxLabs -- make sure we can't have more than max labs
    and not exists(
        select 1
        from Labs
        where LabId = @labId
    )
    
    -- insert lab users
    insert into LabUsers(LabUserName, LabId)
    select
        @userName as LabUserName
    ,   @labId as LabId
    where @labId is not null
    
    -- return labId
    select isnull(@labId,0)
    commit tran
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this question in which I have a SQL Server Compact Edition database
I am using the SQL Server PHP Driver, I think this question can be
I recently asked this question: MS SQL share identity seed amongst tables (Many people
My question is similar to this MySQL question, but intended for SQL Server: Is
I have two databases DB_OLD and DB_NEW, both on SQL Server 2005, and I
My question is similar to Upgrading SQL Server 2000 to 2005 or 2008 -
In SQL Server 2008 the isoweek can be found with this: SELECT datepart(iso_week, getdate())
I'm trying to test the first answer to this question: SQL - message schema
This question originates from a discussion on whether to use SQL ranking functionality or
Like this question , except T-SQL instead of php. 206275947 = 2062759.47 etc. The

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.