Insert into 2 tables with id from first - c#

I have 2 tables
tbl_orgs:
tbl_orgs
and tbl_location_records:
tbl_location_records
I am using a stored procedure to insert data into these tables.
Insert Organization
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spInsOrg]
(#orgName nvarchar(50),
#orgCity nvarchar(50),
#orgArea nvarchar(50),
#orgTel nvarchar(50),
#orgEmail nvarchar(50),
#orgType nvarchar(50),
#orgStatus nvarchar(50),
#strOwner nvarchar(50),
#db_tstamp datetime2)
AS
SET NOCOUNT OFF;
INSERT INTO [tbl_orgs] ([orgName], [orgCity], [orgArea], [orgTel], [orgEmail], [orgType], [orgStatus], [strOwner], [db_tstamp])
VALUES (#orgName, #orgCity, #orgArea, #orgTel, #orgEmail, #orgType, #orgStatus, #strOwner, #db_tstamp);
SELECT
orgID, orgName, orgCity, orgArea, orgTel, orgEmail, orgType,
orgStatus, strOwner, db_tstamp
FROM
tbl_orgs
WHERE
(orgID = SCOPE_IDENTITY())
Insert Location Record
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spInsLoc]
(#userID int,
#orgID int,
#jobID int,
#strLat numeric(18, 0),
#strLong numeric(18, 0),
#strOwner varchar(50),
#db_tstamp datetime2)
AS
SET NOCOUNT OFF;
INSERT INTO [tbl_location_records] ([userID], [orgID], [jobID], [strLat], [strLong], [strOwner], [db_tstamp])
VALUES (#userID, #orgID, #jobID, #strLat, #strLong, #strOwner, #db_tstamp);
SELECT
recordID, userID, orgID, jobID, strLat, strLong, strOwner, db_tstamp
FROM
tbl_location_records
WHERE
(recordID = SCOPE_IDENTITY())
I want to use single form to add inserted organization's location record once organization record successfully inserted.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["IBS_3"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spInsOrg", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("orgName", SqlDbType.NVarChar).Value = txtOrgName.Text;
cmd.Parameters.Add("orgCity", SqlDbType.NVarChar).Value = txtCity.Text;
cmd.Parameters.Add("orgArea", SqlDbType.NVarChar).Value = txtArea.Text;
cmd.Parameters.Add("orgTel", SqlDbType.NVarChar).Value = txtTele.Text;
cmd.Parameters.Add("orgEmail", SqlDbType.NVarChar).Value = txtEmail.Text;
cmd.Parameters.Add("orgType", SqlDbType.NVarChar).Value = txtOrgType.Text;
cmd.Parameters.Add("orgStatus", SqlDbType.NVarChar).Value = txtStatus.Text;
cmd.Parameters.Add("#strOwner", SqlDbType.VarChar).Value = User.Identity.Name;
cmd.Parameters.Add("#db_tstamp", SqlDbType.DateTime2).Value = DateTime.Now;
conn.Open();
cmd.ExecuteNonQuery();
SqlCommand cmdloc = new SqlCommand("spInsLoc", conn);
cmdloc.CommandType = CommandType.StoredProcedure;
cmdloc.Parameters.Add("orgID", SqlDbType.Int).Value =
}
}
Trying to get some understanding from this link but I m clueless on this..
Inserting to one table, insert the ID to second table
Any help appreciated.
Thanks.

Add output parameter to the first stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spInsOrg]
(
#orgID int output,
#orgName nvarchar(50),
#orgCity nvarchar(50),
#orgArea nvarchar(50),
#orgTel nvarchar(50),
#orgEmail nvarchar(50),
#orgType nvarchar(50),
#orgStatus nvarchar(50),
#strOwner nvarchar(50),
#db_tstamp datetime2
)
AS
SET NOCOUNT OFF;
INSERT INTO [tbl_orgs] ([orgName], [orgCity], [orgArea], [orgTel], [orgEmail], [orgType], [orgStatus], [strOwner], [db_tstamp]) VALUES (#orgName, #orgCity, #orgArea, #orgTel, #orgEmail, #orgType, #orgStatus, #strOwner, #db_tstamp);
SELECT #orgID = SCOPE_IDENTITY()
add output param to command..
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spInsOrg", conn);
cmd.CommandType = CommandType.StoredProcedure;
var outParam = cmd.Parameters.Add("#orgID", SqlDbType.Int);
outParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add("#orgName", SqlDbType.NVarChar).Value = txtOrgName.Text;
cmd.Parameters.Add("#orgCity", SqlDbType.NVarChar).Value = txtCity.Text;
cmd.Parameters.Add("#orgArea", SqlDbType.NVarChar).Value = txtArea.Text;
cmd.Parameters.Add("#orgTel", SqlDbType.NVarChar).Value = txtTele.Text;
cmd.Parameters.Add("#orgEmail", SqlDbType.NVarChar).Value = txtEmail.Text;
cmd.Parameters.Add("#orgType", SqlDbType.NVarChar).Value = txtOrgType.Text;
cmd.Parameters.Add("#orgStatus", SqlDbType.NVarChar).Value = txtStatus.Text;
cmd.Parameters.Add("#strOwner", SqlDbType.VarChar).Value = User.Identity.Name;
cmd.Parameters.Add("#db_tstamp", SqlDbType.DateTime2).Value = DateTime.Now;
conn.Open();
cmd.ExecuteNonQuery();
var orgId = (int)outParam.Value;
SqlCommand cmdloc = new SqlCommand("spInsLoc", conn);
cmdloc.CommandType = CommandType.StoredProcedure;
}

Related

Procedure or function Proc_PIP_Employee has too many arguments specified

I am getting error
Procedure or function Proc_PIP_Employee has too many arguments specified
when trying to call procedure Proc_PIP_Employee from C# code. The count of parameters checked and those are same. Also datatypes are same. Even after that getting the same error.
C# code is
public int Add_Record(Employee emp)
{
try
{
if (con.State != ConnectionState.Open)
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
SqlParameter RETURN_VALUE_OUTPUT = new SqlParameter();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "dbo.Proc_PIP_Employee";
cmd.Parameters.Add("#Flag", SqlDbType.Int).Value = 1;
cmd.Parameters.Add("#Empid", SqlDbType.Int).Value = 0;
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = emp.Name ;
cmd.Parameters.Add("#Designation", SqlDbType.VarChar).Value = emp.Designation;
cmd.Parameters.Add("#Department", SqlDbType.VarChar).Value = emp.Department;
cmd.Parameters.Add("#DateofJoin", SqlDbType.DateTime).Value = emp.Dateofjoin;
cmd.Parameters.Add("#Phone", SqlDbType.VarChar).Value = emp.Phone;
cmd.Parameters.Add("#Isactive", SqlDbType.Int).Value = emp.IsActive;
cmd.Parameters.Add("#LoginUser", SqlDbType.NVarChar).Value = "admin";
RETURN_VALUE_OUTPUT = cmd.Parameters.Add("#ReturnId",SqlDbType.Int);
RETURN_VALUE_OUTPUT.Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
ReturnID = Convert.ToInt32(RETURN_VALUE_OUTPUT.Value.ToString());
}
}
catch (SqlException ex)
{
}
return ReturnID;
}
The stored procedure is:
ALTER PROCEDURE [dbo].[Proc_PIP_Employee]
#Flag int,
#Empid int,
#Name varchar(500),
#Designation varchar(200),
#Department varchar(200),
#DateofJoin datetime,
#Phone varchar(3000),
#Isactive int,
#LoginUser nvarchar(500)
AS
BEGIN
SET NOCOUNT ON ;
DECLARE #errorMessage VarChar(8000),
#errorSeverity Int,
#errorState Int,
#ReturnId Int,
#AlCode varchar(50),
#AlDesc varchar(1000),
#AlOp varchar(50),
#AlStatus varchar(50)
BEGIN TRY
BEGIN TRANSACTION
IF (#Flag = 1)
BEGIN
IF EXISTS (SELECT 1 FROM dbo.PIP_Employee
GROUP BY Name, Phone
You're adding an OUTPUT parameter for this stored procedure to your C# code - but there's no #ReturnId OUTPUT parameter in your stored procedure interface:
SqlParameter RETURN_VALUE_OUTPUT = new SqlParameter();
RETURN_VALUE_OUTPUT = cmd.Parameters.Add("#ReturnId",SqlDbType.Int);
RETURN_VALUE_OUTPUT.Direction = ParameterDirection.Output;
If you attempted to capture the return value - then use ParameterDirection.ReturnValue instead
SqlParameter RETURN_VALUE_OUTPUT = new SqlParameter();
RETURN_VALUE_OUTPUT = cmd.Parameters.Add("#ReturnId",SqlDbType.Int);
RETURN_VALUE_OUTPUT.Direction = ParameterDirection.ReturnValue;

Procedure or function 'spRegistrantsGridView' expects parameter '#RegistrantId', which was not supplied

I am using a GridView, and I followed instructions here: http://www.aspsnippets.com/Articles/GridView-CRUD-Select-Insert-Edit-Update-Delete-using-Single-Stored-Procedure-in-ASPNet.aspx
Now I am getting the error: Procedure or function 'spRegistrantsGridView' expects parameter '#RegistrantId', which was not supplied
This is my StoredProcedure:
ALTER PROCEDURE [dbo].[spRegistrantsGridView]
#Action nvarchar(10),
#RegistrantId int,
#FirstName nvarchar(20),
#LastName nvarchar(25),
#AddressLine1 nvarchar(50),
#AddressLine2 nvarchar(50),
#City nvarchar(30),
#State nvarchar(2),
#Zip nvarchar(10),
#Country nvarchar(20),
#Phone nvarchar(15),
#PhoneExt nvarchar(4),
#Email nvarchar(50),
#MemberId bigint,
#Comments nvarchar(300)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
--SELECT
IF #Action = 'SELECT'
BEGIN
SELECT RegistrantId,
FirstName,
LastName,
AddressLine1,
AddressLine2,
City,
State,
Zip,
Country,
Phone,
PhoneExt,
Email,
Comments
FROM Registrant
END
--INSERT
IF #Action = 'INSERT'
BEGIN
INSERT INTO Registrant(
FirstName,
LastName,
AddressLine1,
AddressLine2,
City,
State,
Zip,
Country,
Phone,
PhoneExt,
Email,
MemberId,
Comments)
VALUES (
#FirstName,
#LastName,
#AddressLine1,
#AddressLine2,
#City,
#State,
#Zip,
#Country,
#Phone,
#PhoneExt,
#Email,
#MemberId,
#Comments)
END
--UPDATE
IF #Action = 'UPDATE'
BEGIN
UPDATE Registrant SET
FirstName = #FirstName,
LastName = #LastName,
AddressLine1 = #AddressLine1,
AddressLine2 = #AddressLine2,
City = #City,
State = #State,
Zip = #Zip,
Country = #Country,
Phone = #Phone,
PhoneExt = #PhoneExt,
Email = #Email,
MemberId = #MemberId,
Comments = #Comments
WHERE RegistrantId = #RegistrantId
END
--DELETE
IF #Action = 'DELETE'
BEGIN
DELETE FROM Registrant
WHERE RegistrantId = #RegistrantId
END
END
And the part of my C# where it throws the error (specifically at sda.Fill(dt);):
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
The parameter #RegistrantId wasn't added when calling the stored procedure.
Add the parameter to your code like so:
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
{
cmd.CommandType = CommandType.StoredProcedure;
// missing parameter
cmd.Parameters.AddWithValue("#RegistrantId", [insert id]);
cmd.Parameters.AddWithValue("#Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
EDIT
Now your SP is in your question the issue is you have multiple parameters specified but you're only adding one in your c# code. Either remove the params from your SP or make them optional by adding = null
e.g.
ALTER PROCEDURE [dbo].[spRegistrantsGridView]
#Action nvarchar(10),
#RegistrantId int = null,
#FirstName nvarchar(20) = null,
...

Using Rollback transaction with datatable sql

My project works properly but my issue is when there's an error occured in the second SP spInsertCorpPlan there is no value inserted in CorporationPlan while there is a value inserted in First table CorporationContact.
How to Rollback this.?
Please help.
for (int row = 0; row < dtContact.Rows.Count; row++)
{
SqlCommand cmdContact = new SqlCommand("_spInsertCorpContact", _DentalConOpen());
cmdContact.CommandType = CommandType.StoredProcedure;
cmdContact.Parameters.Add("#CorpCode", SqlDbType.VarChar).Value = Corporation.CorpCode;
cmdContact.Parameters.Add("#ContactType", SqlDbType.VarChar).Value = dtContact.Rows[row][0].ToString();
cmdContact.Parameters.Add("#AreaCode", SqlDbType.VarChar).Value = dtContact.Rows[row][1].ToString();
cmdContact.Parameters.Add("#ContactNo", SqlDbType.VarChar).Value = dtContact.Rows[row][2].ToString();
cmdContact.Parameters.Add("#User", SqlDbType.VarChar).Value = Corporation.User;
cmdContact.ExecuteNonQuery();
cmdContact.Dispose();
cmdContact.Connection.Close();
}
for (int row = 0; row < dtPlan.Rows.Count; row++)
{
SqlCommand cmdPlan = new SqlCommand("_spInsertCorpPlan", _DentalConOpen());
cmdPlan.CommandType = CommandType.StoredProcedure;
cmdPlan.Parameters.Add("#CorpCode", SqlDbType.VarChar).Value = Corporation.CorpCode;
cmdPlan.Parameters.Add("#PlanID", SqlDbType.VarChar).Value = dtPlan.Rows[row][0].ToString();
cmdPlan.Parameters.Add("#EffectiveDate", SqlDbType.DateTime).Value = Convert.ToDateTime(dtPlan.Rows[row][2]);
cmdPlan.Parameters.Add("#ExpiryDate", SqlDbType.DateTime).Value = Convert.ToDateTime(dtPlan.Rows[row][3]);
cmdPlan.Parameters.Add("#User", SqlDbType.VarChar).Value = Corporation.User;
cmdPlan.ExecuteNonQuery();
cmdPlan.Dispose();
cmdPlan.Connection.Close();
}
My Stored Procedures:
ALTER PROCEDURE [dbo].[_spInsertCorpContact]
#CorpCode varchar(20),
#ContactType varchar(1),
#AreaCode varchar(10),
#ContactNo varchar(20),
#User varchar (50)
AS
BEGIN
Insert into CorporationContact
(CorpCode,
ContactType,
AreaCode,
ContactNo,
CreateBy,
CreateDate,
UpdateBy,
UpdateDate)
values
(#CorpCode,
#ContactType,
#AreaCode,
#ContactNo,
#User,
GETDATE(),
'',
null
)
END
ALTER PROCEDURE [dbo].[_spInsertCorpPlan]
#CorpCode varchar(20),
#PlanID varchar(20),
#EffectiveDate DATETIME,
#ExpiryDate DATETIME,
#User varchar (50)
AS
BEGIN
Insert into CorporationPlan
(CorporationPlanID,
CorpCode,
PlanCode,
EffectiveDate,
ExpiryDate,
CreateBy,
CreateDate,
UpdateBy,
UpdateDate)
values
(#CorpCode+#PlanID,
#CorpCode,
#PlanID,
#EffectiveDate,
#ExpiryDate,
#User,
GETDATE(),
'',
null
)
END
You can use SqlTransaction to achieve this. See the sample on this MSDN page. However, make sure you the right isolation level otherwise you might end up creating deadlocks.
Essentially, your code would look something like this:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var transaction = connection.BeginTransaction();
try
{
// Initialize and execute the first command
SqlCommand command = GetFirstCommand();
command.Connection = connection;
command.ExecuteNonQuery();
// Initialize and execute the first command
command = GetSecondCommand();
command.Connection = connection;
command.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
throw;
}
}

Procedure or function 'usp_User_Info2' expects parameter '#UserName', which was not supplied

I am using ASP.NET 4.0 and SQL Server 2008 R2.I am want to Insert the datas using Stored procedure for the "User register" webpage. Whenever i insert the data, the error display as "Procedure or function 'usp_User_Info2' expects parameter '#UserName', which was not supplied".But I entered all required fields except SNo (Identity column) and Vendor_ID (Computed column).What the solution for this ? And also I want "Vendor_ID" display in the message box after insert.
CREATE TABLE User_Info2
(
SNo int Identity (2000,1) ,
Vendor_ID AS 'VEN' + CAST(SNo as varchar(16)) PERSISTED PRIMARY KEY,
UserName VARCHAR(16) NOT NULL,
User_Password VARCHAR(12) NOT NULL,
User_ConPassword VARCHAR(12) NOT NULL,
User_FirstName VARCHAR(25) NOT NULL,
User_LastName VARCHAR(25) SPARSE NULL,
User_Title VARCHAR(35) NOT NULL,
User_EMail VARCHAR(35) NOT NULL,
User_PhoneNo VARCHAR(14) NOT NULL,
User_MobileNo VARCHAR(14)NOT NULL,
User_FaxNo VARCHAR(14)NOT NULL,
UserReg_Date DATE DEFAULT GETDATE()
)
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_User_Info2]
#UserName VARCHAR(30),
#User_Password VARCHAR(12),
#User_ConPassword VARCHAR(12),
#User_FirstName VARCHAR(25),
#User_LastName VARCHAR(25),
#User_Title VARCHAR(35),
#User_OtherEMail VARCHAR(30),
#User_PhoneNo VARCHAR(14),
#User_MobileNo VARCHAR(14),
#User_FaxNo VARCHAR(14)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO User_Info2 (UserName,User_Password,User_ConPassword,User_FirstName,User_LastName,
User_Title,User_OtherEmail,User_PhoneNo,User_MobileNo,User_FaxNo)
VALUES (#UserName,#User_Password,#User_ConPassword,#User_FirstName,#User_LastName,
#User_Title,#User_OtherEMail,#User_PhoneNo,#User_MobileNo,#User_FaxNo)
END
protected void BtnUserNext_Click(object sender, EventArgs e)
{
SqlConnection SqlCon = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_User_Info2";
cmd.Parameters.Add("#User_Email", SqlDbType.VarChar).Value = txtUserName.Text.Trim();
cmd.Parameters.Add("#User_Password",SqlDbType.VarChar).Value = txtRegPassword.Text;
cmd.Parameters.Add("#User_ConPassword",SqlDbType.VarChar).Value = txtRegConPassword.Text;
cmd.Parameters.Add("#User_FirstName",SqlDbType.VarChar).Value = txtRegFName.Text.Trim();
cmd.Parameters.Add("#User_LastName",SqlDbType.VarChar).Value = txtRegLName.Text.Trim();
cmd.Parameters.Add("#User_Title",SqlDbType.VarChar).Value = txtRegTitle.Text.Trim();
cmd.Parameters.Add("#User_OtherEmail", SqlDbType.VarChar).Value = txtOtherEmail.Text;
cmd.Parameters.Add("#User_PhoneNo",SqlDbType.VarChar).Value = txtRegTelephone.Text;
cmd.Parameters.Add("#User_MobileNo", SqlDbType.VarChar).Value = txtRegMobile.Text.Trim();
cmd.Parameters.Add("#User_FaxNo", SqlDbType.VarChar).Value = txtRegFax.Text.Trim();
cmd.Connection = SqlCon;
try
{
SqlCon.Open();
cmd.ExecuteScalar();
}
finally
{ string url = "../CompanyBasicInfo.aspx?Parameter=" + Server.UrlEncode
("+ Vendor_ID +");
ClientScript.RegisterStartupScript(this.GetType(), "callfunction",
"alert('Login created successfully for "+ Vendor_ID +"');
window.location.href = '" + url + "';", true);
SqlCon.Close();
}
}
cmd.Parameters.Add("#User_Email", SqlDbType.VarChar).Value = txtUserName.Text.Trim();
should be:
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = txtUserName.Text.Trim();
To get the identity column add this at the bottom of your stored procedure:
SELECT SCOPE_IDENTITY() 'Id'
And get the value from ExecuteScalar:
Vendor_ID = "VEN" + ((int)cmd.ExecuteScalar()).ToString();

returning int value from stored procedure and check it in asp.net code to validate login form [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
returning int value from stored procedure and check it in asp.net code to validate login form
hello all please i need help in this code as it is stored procedure validate username and password , the problem here is that form validate any data even it doesn't stored in database and i tried to fix code many times but really i haven't any more thing to do in it , any one can help me to solve this problem
this is stored procedure
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[login_procedure] #username Varchar =50, #password varchar=50, #result int OUTPUT
as
Declare #user_name varchar , #pass_word varchar
Set #user_name = #username
Set #pass_word = #password
if EXISTS (select #username , #password from data where username= #user_name and password=#pass_word)
select #result=1
else
select #result=0
and this is asp.net code
SqlConnection conn = new SqlConnection ("Data Source=ANAGUIB-LAPNEW\\SQLEXPRESS;Initial Catalog=account;Integrated Security=True");
SqlCommand cmd = new SqlCommand("login_procedure", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramReturnValue = new SqlParameter();
paramReturnValue.ParameterName = "#result";
paramReturnValue.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(paramReturnValue);
cmd.Parameters["#result"].Direction = ParameterDirection.Output;
conn.Open();
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox2.Text);
int resultID = Convert.ToInt32(cmd.ExecuteScalar());
if (Convert.ToInt32(resultID) == 0)
{
Response.Redirect("hello.aspx");
}
else
{
Response.Write("error");
}
conn.Close();
}
Your stored-procedure has OUTPUT parameter and it is good practice to access value of output parameter after closing the connection.
I've changed proc.
ALTER PROCEDURE login_procedure
#username Varchar(50),
#password varchar(50),
#result int OUTPUT
AS
IF EXISTS (select username from data where username= #username and password=#password)
set #result=1
else
set #result=0
Demo: How to pass parameters (IN and OUT)?
SqlConnection cn = new SqlConnection(cnstr);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "login_procedure";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter param1 = new SqlParameter("#username", System.Data.SqlDbType.VarChar, 50);
SqlParameter param2 = new SqlParameter("#password", System.Data.SqlDbType.VarChar, 50);
SqlParameter resultParam= new SqlParameter("#result", System.Data.SqlDbType.Int);
resultParam.Direction = System.Data.ParameterDirection.Output;
param1.Value = TextBox1.Text;
param2.Value = TextBox2.Text;
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);
cmd.Parameters.Add(resultParam);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
int retVal;
int.TryParse(resultParam.Value.ToString(),out retVal);
if(retVal==1)
//
else
//
In this code
if EXISTS (select #username ,
#password
from data
where username= #user_name and password=#pass_word)
select #result=1
else
select #result=0
You are returning 1 if the given input is validated in your C# code you are giving error when the return value is not 0, that is why every input even which does not exist in your table is validated.Try this;
if (resultID == 1)
{
Response.Redirect("hello.aspx");
}
else
{
Response.Write("error");
}
And you do not have to Convert the return value of stored procedure twice, once is enough.

Categories