Click here to Skip to main content
15,891,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI All


Can someone help me for this please.

I have a column QuesId with question numbers 1,2,3.....10 .
This column is not a primary key.
My Table:

BokID (PK) not Null QuesId Question

1 1 Question1
2 2 Question2
.....
.....
....


10 10 Question10



And if one of the question is deleted then QuesId column should get updated with sequencial numbers.


Many Thanks
Posted

1 solution

Hello.
You should cteate trigger to achieve this goal.
Try this one:
SQL
CREATE TRIGGER [dbo].[trg_DeleteQuestion]
    ON  [dbo].[tasks]
 AFTER DELETE
    AS 
BEGIN
    SET NOCOUNT ON;

    MERGE tasks AS t
    USING (SELECT ROW_NUMBER() OVER(ORDER BY BokID) AS position,
                  tasks.*
                  FROM tasks
         ) AS s
        ON t.BokID = s.BokID
      WHEN MATCHED
      THEN UPDATE SET t.QuesID = s.position;
END


upd
If we have an additional column, then we should write additional condition for it. We should also use DELETED table, which contains deleted row.
SQL
CREATE TRIGGER [dbo].[trg_DeleteQuestion]
    ON  [dbo].[tasks]
 AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;

	MERGE tasks AS t
	USING (SELECT ROW_NUMBER() OVER(ORDER BY tasks.BokID, tasks.Stage) AS position,
	              tasks.*
	         FROM tasks
	         JOIN DELETED AS d
	           ON d.Stage = tasks.Stage
	      ) AS s
	   ON t.BokID = s.BokID AND
	      t.Stage = s.Stage
	 WHEN MATCHED
     THEN UPDATE SET t.QuesID = s.position;
END


For more information please see
Triggers[^]
Merge clause[^]
Good luck
 
Share this answer
 
v2
Comments
babli3 6-Dec-13 6:03am    
Ok Thank you I will try this.
babli3 6-Dec-13 6:37am    
H THis is updating all the rows thats fine. But in my table there are 3 stages where each stage is having they own set of questions.
Assume: Stage1
question1 .......question10

Stage2
Question1......Question5

How can I updatedelending on each stage.

Thank you so much.
skydger 6-Dec-13 7:07am    
You are welcome!
I suppose, the better way to to this, is to add a new column for stages.
like
BokID QuesId StageCode Question

1 1 1 Question1
2 2 1 Question2
.....
10 10 1 Question10
11 1 2 Question1
.....
20 10 2 Question10
.....

Then you can easily update only stage desired. If this solution is acceptable, the trigger should be modified a little.
skydger 6-Dec-13 9:08am    
I've updated solution for this task. I also added two links which might be helpful.
babli3 6-Dec-13 10:18am    
Thank you so much...its working...u solved my big problem.thanks once again

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900