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

  • SEARCH
  • Home
  • 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 9208933
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T00:43:28+00:00 2026-06-18T00:43:28+00:00

I have a small SQL based challenge that i’m trying to solve to better

  • 0

I have a small SQL based challenge that i’m trying to solve to better my knowledge of Dynamic SQL.

My requirements are as follows.

I created a table that looks as follows:

CREATE TABLE Prison_Doors
(
 DoorNum INT IDENTITY(1,1) PRIMARY KEY,
 DoorOpen BIT,
 DoorClosed BIT,
 Trips INT
 )
 GO

I need to Create a Dynamic SQL Proc to insert 50 Door numbers and assign them as closed.

Expected result of proc:

|DoorNum|DoorOpen|DoorClosed|Trips|
|-------|--------|----------|-----|
|   1   |    0   |     1    |null |
|-------|--------|----------|-----|
|---------All the way to 50-------|
|-------|--------|----------|-----|
|   50  |    0   |     1    |null |

This is what I have written but it is not inserting:

BEGIN
DECLARE @SQL VARCHAR(8000)
DECLARE @Index INT
SET @Index=1


WHILE (@Index<=50)
BEGIN
    SET @SQL= 'INSERT INTO Prison_Doors(DoorNum,DoorOpen,DoorClosed)
                    VALUES('+CAST(@Index AS VARCHAR)+',0,1),'
    SET @Index=@Index+1
END

SET @SQL = SUBSTRING(@SQL, 1, LEN(@SQL)-1)
EXEC(@SQL)

END

I would like to know what I am doing wrong.

after all of this is done I then need to run another loop to start at door one and change every second door to open and change trips to one and then increment to every 3 doors to open and trips becomes 2 and this incrementation continues until all doors are open which will then select the number of trips that it took.

I hope somebody can assist me with this as I am new to Dynamic SQL and I just need some guidance and not the complete solution.

Help is much appreciated 🙂

  • 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-18T00:43:29+00:00Added an answer on June 18, 2026 at 12:43 am

    The error you got is because you are trying to insert into an identity column DoorNumber:

    DoorNum INT IDENTITY(1,1) PRIMARY KEY,
    

    Remove that columns from the column list, instead of:

    INSERT INTO Prison_Doors(DoorNum,DoorOpen,DoorClosed)
    

    remove that column DoorNum:

    INSERT INTO Prison_Doors(DoorOpen,DoorClosed)
    ...
    

    However, there is no need for dynamic SQL to do that, you can do this using an anchor table like this:

     WITH temp 
     AS
     (
       SELECT n
       FROM (VALUES(1), (2), (3), (4)) temp(n)
     ), nums
     AS
     (
       SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS n
       FROM temp t1, temp t2, temp t3
     )
     INSERT INTO Prison_Doors(DoorOpen, DoorClosed)
     SELECT 0 AS DoorOpen, 1 AS DoorClosed
     FROM nums
     WHERE n <= 50;
    

    Live Demo.


    Update:

    What my code does line by line?

    Generating Sequence of numbers:

    The first problem was generating a sequence of 50 numbers from 1 to 50, I used an anchor table with only four rows from 1 to 4 like this:

    SELECT n
    FROM (VALUES(1), (2), (3), (4)) temp(n);
    

    This syntax using the VALUES is new to SQL-Server-2008, it is called Row Value Constructor. After the VALUES, you assign an alias of the table and the target columns in parentheses like temp(n).

    For old versions you have to use something like :

    SELECT n
    FROM 
    (
       SELECT 1 AS n
       UNION ALL 
       SELECT 2
       UNION ALL
       SELECT 3
       UNION ALL 
       SELECT 4
    ) AS temp;
    

    This will give you only 4 rows, but we need to generate 50. Thats why I CROSS JOIN this table three time with itself using:

    FROM temp t1, temp t2, temp t3
    

    It is the same as

    FROM temp t1
    CROSS JOIN temp t2
    CROSS JOIN temp t3
    

    This will multiply these rows 64 times, 4 rows3 = 64 rows:

    1   1   1
    1   2   1
    1   3   1
    1   4   1
    2   1   1
    2   2   1
    2   3   1
    2   4   1
    ....
    3   1   4
    3   2   4
    3   3   4
    3   4   4
    4   1   4
    4   2   4
    4   3   4
    4   4   4
    

    The Use Of ROW_NUMBER() Function:

    Then using the ROW_NUMBER() will give us a ranking number from 1 to 64 like this:

     WITH temp 
     AS
     (
       SELECT n
       FROM (VALUES(1), (2), (3), (4)) temp(n)
     )
     SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS n
     FROM temp t1, temp t2, temp t3;
    

    Note that: ROW_NUMBER requires an ORDER BY clause, in or case it doesn’t matter the order, so I used (SELECT 1).

    There is also another way for generating a sequence numbers with out the use of ROW_NUMBER, it also depends on the CROSS JOIN, with an anchor table like:

     WITH temp 
     AS
     (
       SELECT n
       FROM (
             VALUES(0), (1), (2), (3), (4), (5), (6), (7), (8), (9)
            ) temp(n)
     ), nums
     AS
     (
       SELECT t1.n * 100 + t2.n * 10 + t3.n + 1 AS n
       FROM temp t1, temp t2, temp t3
     )
     SELECT n
     FROM nums 
     ORDER BY n;
    

    Another Way of Generating Sequence Of Numbers


    Common Table Expressions:

    The CTE is called common table expression, and it was introdeced in SQL Server 2005. It is one of the table expressions types that SQL Server supports. The other three are:

    • Derived tables,
    • Views, and
    • Inline table-valued functions.

    It has a lot of important advantages. One of them is let you create a virtual tables that you can reuse them later, like what I did:

     WITH temp 
     AS
     (
       SELECT n
       FROM (VALUES(1), (2), (3), (4)) temp(n)
     ), nums
     AS
     (
       SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS n
       FROM temp t1, temp t2, temp t3
     )
     ...
    

    Here I defined two CTE’s temp then another one nums that ruse that temp so this OL, you can create multiple CTE’s, just put a semicolon, then a new one with the AS clause and two ().


    Insert into one table from another table using INSERT INTO ... SELECT ...

    Now, we have a virtual table nums having rows from 1 to 64, we need to insert the rows from 1 to 50.

    For this, you can use the INSERT INTO ... SELECT ....

    Note that the columns in the INSERT clause are optional, but If you do so, you have to put a value for each row, if not you will got an error, for example if you have four columns and you put only three values in the VALUES clause or in the SELECT clause, then you will got an error. This is not valid for the idenetityt columns which are defined with:

    Identity(1,1)
             ^ ^
             | |
             | ------------------The seed
             The start
    

    In this case you simply ignore that column in the columns list in the INSERT clause and it will have the identity value. There is an option that let you insert a value manually like in the @Raj’s answer.

    Note that: In my answer, I am not inserting the sequence numbers in to that column instead, inserting the values 50 times. But the actual numbers are generating automatically because of the Identity column:

     ...
     INSERT INTO Prison_Doors(DoorOpen, DoorClosed)
     SELECT 0 AS DoorOpen, 1 AS DoorClosed
     FROM nums;
     WHERE n <= 50;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have small web app that generate PDF files as a report. I'm trying
We have a mid-size SQL Server based application that has no indexes defined. Not
I have a small web application based on asp.net 2010 that manages invoices. After
I have a small sql question for you. I have two queries: SELECT tbl_CostPrevisions.Month,
I have small problem with Spring MVC. Basically what I'm trying to do is
I have a .net server based application, that needs to be able to do
I'm using Linq to Sql (in fact it's Dynamic Linq to SQL that allows
I have a PHP application that pulls order information based on a scanned/entered order
I have a client that runs a small business. They need a custom database
We have 70+ SQL Server 2008 databases that need to be copied from an

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.