How to check duplicate records in database through SQL stored procedure by using ASP.net?
Stored Procedure always help to execute group of statement at a time. It saves time and avoids redundancy. This code can be used when unique record has to be inserted in tables of sql. Consistent implementation of logic across applications can be achieved by using stored procedures.
Description - After calling stored procedure, bool value will be retured which helps you to find whether duplicate records are present in database or not.
public bool CheckDuplicateRecords()
{
try
{
CONN = GetConnection();
//This will open the connection.
CONN.Open();
CMD = new SqlCommand("yourStoredProcedurename", CONN);
CMD.CommandType = CommandType.StoredProcedure;
CMD.Parameters.Add("@ChkDuplicateRecord", SqlDbType.Char, 1);
CMD.Parameters["@ChkDuplicateRecord"].Direction = ParameterDirection.Output;
bool Is_duplicate = Convert.ToBoolean(CMD.ExecuteNonQuery());
CONN.Close();
return Is_duplicate;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CMD.Dispose();
//This will close the connection.
CONN.Close();
CONN.Dispose();
}
}
This code will help you to connect to database.
public SqlConnection GetConnection()
{
CONN = new SqlConnection(ConfigurationManager.ConnectionStrings["Keyname"].ToString());
return CONN;
}
You have to put following code in Web.config
<connectionStrings>
<add name="Keyname" connectionString="Data Source=yourPCname\yourSQLServerInstancename;Initial Catalog=yourDatabaseName;User ID =youruseridcredentials;Password=yourPassword" providerName="System.Data.SqlClient"/>
</connectionStrings>