5
Reply

Avoid duplicate entry in database using stored procedure

Saumya Agarwal

Saumya Agarwal

Nov 8 2013 7:37 AM
4.3k
I have a simple form in which the user enters details and as he clicks on SAVE button the details are displayed in a GRIDVIEW on another page. Now I dont want any other user with the same username for which i have made a stored procedure but it doesnt work in the code.

Here in my SP for avoiding duplicate entry.

ALTER PROCEDURE [dbo].[tableuser]

    @userName varchar(50)
   
AS   
IF EXISTS (SELECT 'True' FROM tbl_user WHERE userName=@userName)
BEGIN
 select 'Record already exists'
 select @@identity;
END
BEGIN
    select 'Record Added'
    select @@identity;
END

SP for adding details of user:
ALTER PROCEDURE [dbo].[ADDuser]
    -- Add the parameters for the stored procedure here
(   
    @userName varchar(50),
    @password nvarchar(50),
    @emailAddress nvarchar(50)
)
AS
BEGIN
    INSERT INTO tbl_user(userName,password,emailAddress) values(@userName,@password,@emailAddress)
    SELECT @@IDENTITY;
   
   
END


This is the C# code:

 protected void save_Click(object sender, EventArgs e)
    {
        ClassBAL obj = new ClassBAL();
        DataSet ds = new DataSet();
        obj.userName = uname.Text;
        obj.password = upass.Text;
        obj.emailAddress = umail.Text;
        List<int> preferences = new List<int>();
        foreach (ListItem value in CBL1.Items)
        {
            if (value.Selected)
            {
                preferences.Add(Convert.ToInt32(value.Value));
            }
        }
        obj.preferences = preferences;
        ds=obj.tableuser();

        obj.ADDuser();
        Response.Redirect("UserDisplay.aspx");
    }

I have used DAL and BAL in my application. Everything goes well but duplicate entry occurs.
Pls help...


Answers (5)