Make use of Stored Procedure
Code
string strConnString = ConfigurationManager.ConnectionStrings["constr_sample"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("InsertUser"))
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserName", "Mudassar");
cmd.Parameters.AddWithValue("@Password", "1234");
cmd.Parameters.AddWithValue("@Email", "mak@123.com");
con.Open();
bool success = Convert.ToBoolean(cmd.ExecuteScalar());
if (success)
{
Response.Write("User created");
}
else
{
Response.Write("User exists");
}
con.Close();
}
}
SQL
CREATE PROCEDURE InsertUser
@UserName varchar(100),
@Password varchar(100),
@Email varchar(100)
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT * FROM [Login] WHERE UserName = @UserName)
BEGIN
SELECT 'FALSE'
END
ELSE
BEGIN
INSERT INTO [Login]
VALUES(@UserName, @Password, @UserName)
SELECT 'TRUE'
END
END
GO