0
  • hello all , i wanna create Table in sql Server (Ex: employe) this table have columns (ID, FName, LName, age ..etc

    • i need ID column add auto number for each new row automatic. i Set the Identity specification to yes like this : Identity specification

but if did this setting in ID column i will face another issue like this picture : open this picture

  • now how to make ID column become auto count after delete any rows?

so i thought i should make a loop to add new number in ID value every new record . and count the ID column every deleting row to reset the list of number in ID column .

i think my idea is clear now . so any help in this to make it work . i'm using c# .

Community
  • 1
  • 1
Nouri Yacine
  • 63
  • 13
  • If the ID column is set as auto increament and primary key then you dont have to expcitly provide the value for it. Just add the values for other columns and it will auto increament. Upon deleting any record, the ID will be deleted too and if a new record is added it will have the id of the next record after the deleted one. Lets say if you delete ID 8 and add another record, its ID will be 9 not 8. – Yawar Murtaza Mar 20 '17 at 11:43
  • [this may be helpful](http://stackoverflow.com/questions/510121/reset-autoincrement-in-sql-server-after-delete) This solution is helpful for me. you try it – Rami Far Mar 20 '17 at 12:22
  • @YawarMurtaza yes i set it auto increment , but i was facing this problem in ID 8 and ID 9 if i delete ID 8 the next one should be ID 8 not ID 9 . – Nouri Yacine Mar 20 '17 at 13:42
  • thank you bro @RamishaFarrukh – Nouri Yacine Mar 20 '17 at 13:43
  • It wont be ID 8 as its deleted! thats how the SQL Server Database engine works. This might help http://stackoverflow.com/questions/4288089/reuse-identity-value-after-deleting-rows – Yawar Murtaza Mar 20 '17 at 13:45
  • what if i add two columns (ID , Number) and set ID as auto increament and primary key , and Number as a list numbers to help me list the rows . and i will hide the ID from DatagridView and show the Number as as list .. how to make Number column reset the list from 1,2,3,4 .. etc. every delete? – Nouri Yacine Mar 20 '17 at 14:01
  • OKay let me get this right. In that case when the records is deleted from the middle of the table then you would need to update all the records that come after that deleted one? And if the very first records is delete then you want all the rest of the records' Number column to be updated? Am i getting it right? – Yawar Murtaza Mar 20 '17 at 16:11
  • @YawarMurtaza great my friend that's it .. that's all what i need now . but my friend i did something to make it like what i need.. i just let the ID as auto increament and primary key .. and i just showed the datagrid view row header numbers .. to be looks like Excel .. now i just hide the ID column in run time and the user will now see it . what do you think my friend ? – Nouri Yacine Mar 22 '17 at 07:01

2 Answers2

1

Lets say you have an employee table definition:

CREATE TABLE [dbo].[Employee](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [FirstName] [varchar](50) NULL,
    [LastName] [varchar](50) NULL,
    [DateOfBirth] [datetime] NULL,
    [SequenceNumber] [int] NOT NULL,
    [DateTimeStamp] [datetime] NOT NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Employee] ADD  CONSTRAINT [DF_Employee_DateTimeStamp]  DEFAULT (getdate()) FOR [DateTimeStamp]
GO

The ID is set to primary key and auto increment. The SequenceNumber column is the one we are interested in. It will be kept in sequence as your requirements are. DateTimeStamp is also set to current datetime when a new record is added - just to keep the logs.

Now we have a stored procedure that will add a new employee record:

 CREATE PROCEDURE spAddNewEmployee
                @FirstName AS VARCHAR(50),
                @LASTNAME AS VARCHAR(50),
                @DATEOFBIRTH AS DATETIME            
    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;

        -- Insert statements for procedure here

    DECLARE @LAST_SEQUENCE_NUMBER AS INT;

    SELECT @LAST_SEQUENCE_NUMBER   = MAX([SequenceNumber]) FROM dbo.Employee

    IF(@LAST_SEQUENCE_NUMBER IS NULL)
    BEGIN
        SET @LAST_SEQUENCE_NUMBER = 1;
    END
    ELSE
    BEGIN
        SET @LAST_SEQUENCE_NUMBER = @LAST_SEQUENCE_NUMBER + 1

    END


    INSERT INTO dbo.Employee
    (
           [FirstName]
          ,[LastName]
          ,[DateOfBirth]
          ,[SequenceNumber]      
    )
    VALUES
    (
        @FirstName,
        @LastName,
        @DateOfBirth,
        @LAST_SEQUENCE_NUMBER
    )
    END
    GO

It will retrieve the last SequenceNumber value if its not null (which will be when first record will be added) it will add 1 to it. Next the record will be added along with the auto field DateTimeStamp.

So far so good. Now lets get to the Delete employee part, here is the Delete Employee stored proc:

CREATE PROCEDURE [dbo].[spDeleteEmployee]
                @EmployeeId  AS INT 
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here

    DECLARE @DELETED_SEQUENCE_NUMBER AS INT, @LAST_SEQUENCE_NUMBER AS INT;

    SELECT @LAST_SEQUENCE_NUMBER   =  MAX([SequenceNumber]) FROM dbo.Employee
    SELECT @DELETED_SEQUENCE_NUMBER   = [SequenceNumber] FROM dbo.Employee WHERE ID = @EMPLOYEEID

    DELETE FROM dbo.Employee
    WHERE ID = @EMPLOYEEID

    WHILE(@DELETED_SEQUENCE_NUMBER   <= @LAST_SEQUENCE_NUMBER)
    BEGIN
        UPDATE dbo.Employee
        SET SequenceNumber = @DELETED_SEQUENCE_NUMBER
        WHERE SequenceNumber = @DELETED_SEQUENCE_NUMBER + 1

        SET @DELETED_SEQUENCE_NUMBER = @DELETED_SEQUENCE_NUMBER + 1
    END


END

GO

To keep the SequenceNumber constant incremental first we are getting the last sequence number and the one which is being deleted. Then after deleting the record, we are looping through each record that comes after the deleted one and aligning the SequenceNumber until we reach to the end of the records i.e. while loop condition.

To make it better, you can use of transaction to encapsulate the whole operation.

EDIT: You can also make SequenceNumber column unique:

 ALTER TABLE [dbo].[Employee] ADD CONSTRAINT UQ_SequenceNumber UNIQUE ([SequenceNumber])

Hope this answers your question.

Yawar Murtaza
  • 3,655
  • 5
  • 34
  • 40
  • We find it very useful for audit purposes. It allows us to see which records were added at what date time so that we can look into the most recent once if needed. – Yawar Murtaza Mar 22 '17 at 21:15
  • thank you so much my friend but m so sorry i'm not good in SQL programming and new in c# i can understand your code but i don't know how to do it in sql and make somechanges on the code . i think i will go to someone and show him your code maybe he will help me to set it in my program.. thank you so much again . – Nouri Yacine Mar 22 '17 at 22:36
1

In my opinion, if you just want to display the sequential numbers in the Gridview, you don't need to bother about the underlying Auto Increment Primary Key.

You can use <%# Container.DataItemIndex + 1 %> to display that sequential number.

Please see the example below:

<asp:GridView ID="GridView1" runat="server"  AutoGenerateColumns="False" >
<Columns>
        <asp:TemplateField HeaderText="#">
            <ItemTemplate>
                <%# Container.DataItemIndex + 1 %>
            </ItemTemplate>
            <ItemStyle Font-Bold="false" />
        </asp:TemplateField>
        <asp:BoundField DataField="FirstName" HeaderText="FirstName"></asp:BoundField>
        <asp:BoundField DataField="LastName" HeaderText="LastName"></asp:BoundField>
</Columns>
</asp:GridView>
TTCG
  • 8,805
  • 31
  • 93
  • 141