Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Condition insert query in while loop in sql server

enter image description hereI want to insert count values in table with conditions using while loop.
I want to result like

EmpID EMpNo IsActive IsScience
1 1 1 1
2 2 1 1
3 3 1 1
. . . .
27 27 1 0
28 28 1 0
. . . .
565 565 1 0
BEGIN
DECLARE @i int = 0
WHILE @i < 565 
BEGIN
    SET @i = @i + 1
    while @i < 26
    BEGIN
        INSERT INTO [dbo].[T_Emp] ([EmpID],[EMpNo],[IsActive],[IsScience])
        VALUES(@i,@i,1,1);
    END
    while @i > 26 AND @i <565
    BEGIN
        INSERT INTO [dbo].[T_Emp] ([EmpID],[EMpNo],[IsActive],[IsScience])
        VALUES(@i,@i,1,0);
    END
END
END

As you can see I want to change IsScience after @i > 26 .
Also My @i isn’t incremented. What I am doing wrong with looping.
My loop executing executing wrongly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

remove multi time while loop in your code use this code

BEGIN
    DECLARE @i int = 0
    WHILE @i < 565 
    BEGIN
      SET @i = @i + 1
      IF(@i < 26)
      BEGIN
        INSERT INTO [dbo].[T_Emp]
        ([EmpID],[EMpNo],[IsActive],[IsScience])
        VALUES(@i,@i,1,1);
      END
      IF(@i > 26 AND @i <565)
      BEGIN
        INSERT INTO [dbo].[T_Emp]
        ([EmpID],[EMpNo],[IsActive],[IsScience])
        VALUES(@i,@i,1,0);
      END
    END
END

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading