简体   繁体   中英

C# Code for generating Unique ID for each row inserted into SQL Server 2008 R2

I have written a unique ID generating function that generates a ID every time a new row is inserted into the database. But sometimes it gives same ID for every row. I can't find out what is the problem exactly happening that time. I give you the code for insert into database and code for ID generate. Please review the code and tell me if there is any logical error or not-

// Daily sales report entry codeing…………………………………………………………………………………………………………………
public string GetSalesTeam(SalesTeam st)
{
        try
        {
            SqlConnection con = SqlConnDAC.CreateConn();
            SqlCommand cmd = new SqlCommand("Insert into DSR values(@v1,@v2,@v3,@v4,@v5,@v6,@v7,@v8,@v9,@v10,@v11,@v12,@v13,@v14,@v15,@v16)", con);

            IDGen.varr   = DSR_IDGen(); //Calling id generate function 

            cmd.Parameters.AddWithValue("@v1", st.Sl_No);
            cmd.Parameters.AddWithValue("@v2", st.User_ID);
            cmd.Parameters.AddWithValue("@v3", st.Name);
            cmd.Parameters.AddWithValue("@v4", st.Branch);
            cmd.Parameters.AddWithValue("@v5", st.Desg);
            cmd.Parameters.AddWithValue("@v6", st.Visiting_Date);
            cmd.Parameters.AddWithValue("@v7", st.Name_Of_Client);
            cmd.Parameters.AddWithValue("@v8", st.Address);
            cmd.Parameters.AddWithValue("@v9", st.PhNo);
            cmd.Parameters.AddWithValue("@v10",Convert.ToInt32(st.QuoteValue));
            cmd.Parameters.AddWithValue("@v11", st.Remarks);
            cmd.Parameters.AddWithValue("@v12", st.Source);

            cmd.Parameters.AddWithValue("@v13",IDGen.varr);

            cmd.Parameters.AddWithValue("@v14", st.Month);
            cmd.Parameters.AddWithValue("@v15", st.Year);
            cmd.Parameters.AddWithValue("@v16",Convert.ToInt32(st.ClosedValue));
           // cmd.Parameters.AddWithValue("@v17", st.TypeOfCall);

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            return "Success and DSR No.for_ "+st.Name_Of_Client+" = "+IDGen.varr+"";
        }
        catch (Exception e)
        {
            return e.ToString();
        }
}

//ID generate function………………………………………………………..
public string DSR_IDGen()
{
    int i = 0;
    string temp;

    string var;
    var = ("DSR-" + i.ToString()).Trim();
    SqlConnection conID = SqlConnDAC.CreateConn();

    SqlCommand cmdd = new SqlCommand("select DSR_No from DSR", conID);
    conID.Open();

    SqlDataReader dr = cmdd.ExecuteReader();

    while (dr.Read())
    {
        temp = (dr[0].ToString()).Trim();

        if (var == temp)
        {
           i = i + 1;
           var = ("DSR-" + i.ToString()).Trim();
           continue;
        }
    }

    dr.Close();
    conID.Close();

    return var;
}

// a static variable that holds the ID............................
public class IDGen
{
   public static string varr;
}

One word of advice: don't try to make this any more difficult than it is, and don't try to outsmart SQL Server. Why don't you just use the database-provided mechanisms that's already in place for this: an IDENTITY column?

I would recommend you use:

  • an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
  • a computed, persisted column to convert that numeric value to the value you need

So try this:

CREATE TABLE dbo.DSR
  (ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
   DsrID AS 'DSR-' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
   .... your other columns here....
  )

Now, every time you insert a row into DSR without specifying values for ID or DsrID :

INSERT INTO dbo.DSR(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)

then SQL Server will automatically and safely increase your ID value, and DsrID will contain values like DSR-0000001 , DSR-0000002 ,...... and so on - automatically, safely, reliably, no duplicates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM