Below is my method to update the row once the update button is clicked. My SQL Server stored procedure is expecting the existing company name before it has been updated, the new company name and whether it exists or not. The bold part is where it is breaking. When I select edit, I want to parse in the current value in the company name row before I hit update.
protected void CompanyTable_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
using (SqlCommand cmd = new SqlCommand("[updateCompanyName]", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
GridViewRow row = CompanyTable.SelectedRow;
cmd.Parameters.AddWithValue("#CurrentCompanyName", CompanyTable.Rows[e.RowIndex].Cells[0].Controls[0]);
cmd.Parameters.AddWithValue("#NewCompanyName", CompanyInputTextBox.Text).Direction = ParameterDirection.Input;
SqlParameter objisExists = new SqlParameter("#isExists", SqlDbType.Int);
objisExists.Direction = ParameterDirection.Output;
cmd.Parameters.Add(objisExists);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
int isExists = Convert.ToInt32(cmd.Parameters["#isExists"].Value.ToString());
if (isExists == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "111", "AddCompanySuccess();", true);
}
else if (isExists == 1)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "111", "CompanyExistsValidation();", true);
}
}
}
Stored procedure parameters:
ALTER PROCEDURE [dbo].[updateCompanyName]
#CurrentCompanyName VARCHAR(50),
#NewCompanyName VARCHAR(50),
#IsExists INT = 0 OUT
My update in SQL:
DECLARE #CompanyID INT
SELECT #CompanyID = CompanyID
FROM company
WHERE companyname = #CurrentCompanyName
BEGIN
IF EXISTS (SELECT CompanyName FROM company
WHERE companyname = #NewCompanyName )
BEGIN
SET #IsExists = 1
END
ELSE
BEGIN
UPDATE COMPANY
SET CompanyName = #NewCompanyName
WHERE companyid = #CompanyID
SET #IsExists = 0
END
END
PRINT #isexists
Related
I have this web app where a user enters data in a webform using a checkboxlist and a text box to enter a value and date. Those values entered are then updated to a database using a stored procedure.
When using a stored procedure, the webapp works correctly, but if I use an Update statement instead, it updates the database with the values entered by the user times the number of items selected in the database.
For example if there are 11 items in the checkboxlist with all items checked, with the stored procedure, if a user enters 12, each value in the database will be 12, but using the update statement, each value entered will be 132, can anyone explain to me why it does that and if there is a way to get the same results as the stored procedure?
CREATE TABLE AccountTable
(
RowID int IDENTITY(1, 1),
AccountID varchar(2),
AccountName varchar(50),
SeqNum int,
SeqDate datetime
)
CREATE PROCEDURE [ACCOUNTTABLE_UPDATE]
(#SeqNum int,
#SeqDate datetime,
#Account_ID varchar(2)
)
AS
SET NOCOUNT ON
BEGIN
UPDATE AccountTable
SET SeqNum = SeqNum + #SeqNum, SeqDate = #SeqDate
WHERE AccountID = #AccountID
END
C# code:
DateTime dt = DateTime.Now;
DateTime.TryParseExact(datepicker.Text, "mmddyyyy", provider, style out dt);
int i = Int32.Parse(TextBox1.Text);
//DropDownList Binded from database values in another method
SqlConnection con = new SqlConnection(GetConnString());
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[dbo].[Table_Update]";
//Update Query cmd.CommandText = "Update Account Table SET SeqNum = SeqNum + #SeqNum, SeqDate = #SeqDate WHERE AccountID = #AccountID;";
cmd.Parameters.AddWithValue("#SeqNum", SqlDbType.Int).Value = i
cmd.Parameters.AddWithValue("#SeqDate",SqlDbType.DateTime).Value = DateTime.Now;
cmd.Parameters["#Account_ID", SqlDbType.VarChar).Value = CheckBoxList1.SelectedValue;
foreach (ListItem item in CheckBoxList.Items)
{
if (item.Selected)
{
cmd.Parameters["#SeqNum"].Value = i;
cmd.Parameters["#SeqDate"].Value = DateTime.Now;
cmd.Parameters["#Account_ID"].Value = item.Value;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Response.Write(ex.Message);
//Database Exceptions
}
finally
{
con.Close();
}
}
}
How about:
public void data2()
{
DateTime dt = DateTime.Now;
DateTime.TryParseExact(datepicker.Text, "mmddyyyy", provider, style out dt);
int i = Int32.Parse(TextBox1.Text);
int check = 0;
//DropDownList Binded from database values in another method
foreach (ListItem item in CheckBoxList.Items)
{
if (item.Selected)
{
check++;
}
}
using (SqlConnection conn = GetConnString())
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
// cmd.CommandType = CommandType.StoredProcedure;
//cmd.CommandText = "[dbo].[Table_Update]";
cmd.CommandText = "Update Account Table SET SeqNum = SeqNum + #SeqNum, SeqDate = #SeqDate WHERE AccountID = #AccountID";
cmd.Parameters.AddWithValue("#SeqNum", check);
cmd.Parameters.AddWithValue("#SeqDate", DateTime.Now);
cmd.Parameters["#Account_ID", CheckBoxList1.SelectedValue);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
or, it TextBox1.Text is already the number you want to save...
public void data3()
{
DateTime dt = DateTime.Now;
DateTime.TryParseExact(datepicker.Text, "mmddyyyy", provider, style out dt);
int i = Int32.Parse(TextBox1.Text);
//DropDownList Binded from database values in another method
using (SqlConnection conn = GetConnString())
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
// cmd.CommandType = CommandType.StoredProcedure;
//cmd.CommandText = "[dbo].[Table_Update]";
cmd.CommandText = "Update Account Table SET SeqNum = SeqNum + #SeqNum, SeqDate = #SeqDate WHERE AccountID = #AccountID";
cmd.Parameters.AddWithValue("#SeqNum", TextBox1.Text);
cmd.Parameters.AddWithValue("#SeqDate", DateTime.Now);
cmd.Parameters["#Account_ID", CheckBoxList1.SelectedValue);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
NOTE that in both cases, because your SQL contains "SeqNum = SeqNum + #SeqNum", it will save a running total of how many pictures, adding those selected here to any selected before. If you don't want to do that, modify your SQL to "SeqNum = #seqNum" and it will modify to the number selected only during this page load.
I am trying to set up an page to replicate an ATM using C#, ASP.NET and MSSQL (MSSQLEXPRESS if that matters). One part of it is a "new user" page to "sign up" for the "service". The problem is that when I test the page, I get an error message I set up to detect invalid credit card numbers, regardless of the number input. I believe the problem is in either my click event code, my C# query code or in my stored procedure to the event. I think the solution for this is most likely a simple one, but perhaps a pair of fresh eyes will see the problem.
Any help or suggestions would be greatly appreciated.
Code for button click:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string display;
long cardnum;
string strcard = Request.Params.Get("__CREDITCARD");
if (long.TryParse(strcard, out cardnum))
{
string first = Request.Params.Get("__FIRSTNAME");
string middle = Request.Params.Get("__MIDDLENAME");
string last = Request.Params.Get("__LASTNAME");
string email = Request.Params.Get("__EMAIL");
string address = Request.Params.Get("__ADDRESS");
string username = Request.Params.Get("__USERNAME");
string password = Request.Params.Get("__PASSWORD");
int retcode = SqlQueries.changeUserInfo(cardnum, username, password, first, middle, last, email, address, out display);
switch (retcode)
{
case 1:
display = "Credit card number can only contain digits";
Alert.show(Page, this.GetType(), "Input Error", display);
UserDetails.Username = username;
UserDetails.Password = password;
Response.Redirect("HomePage.aspx");
return;
case 0:
display = "Invalid credit card number";
break;
}
}
else
{
display = "Credit card number can only contain digits";
}
Alert.show(Page, this.GetType(), "Input Error", display);
}
Which uses the changeUserInfo method from my SqlQueries class:
public static int changeUserInfo(long cardNum, string username, string password, string strFirstName, string strMiddleName, string strLastName, string strEmail, string strAddress, out string strError)
{
//SQL connection
SqlConnection objConn = new SqlConnection(strconnectionSting);
objConn.Open();
int intReturnValue = -1;
strError = string.Empty;
//If connection is open
if (objConn != null && objConn.State == ConnectionState.Open)
{
//Call to stored procedure: qprtnum_UpdatePartNumber
SqlCommand cmd = new SqlCommand("updateUserInfo", objConn);
cmd.CommandType = CommandType.StoredProcedure;
try
{
cmd.Parameters.Add(new SqlParameter("#CardNum", SqlDbType.Decimal, 150));
cmd.Parameters["#CardNum"].Precision = 18;
cmd.Parameters["#CardNum"].Scale = 0;
cmd.Parameters["#CardNum"].Value = cardNum;
cmd.Parameters.Add(new SqlParameter("#Username", SqlDbType.NVarChar, 50));
cmd.Parameters["#Username"].Value = username;
cmd.Parameters.Add(new SqlParameter("#Password", SqlDbType.NVarChar, 50));
cmd.Parameters["#Password"].Value = password;
cmd.Parameters.Add(new SqlParameter("#FirstName", SqlDbType.NVarChar, 150));
cmd.Parameters["#FirstName"].Value = strFirstName;
cmd.Parameters.Add(new SqlParameter("#MiddleName", SqlDbType.NVarChar, 150));
cmd.Parameters["#MiddleName"].Value = strMiddleName;
cmd.Parameters.Add(new SqlParameter("#LastName", SqlDbType.NVarChar, 150));
cmd.Parameters["#LastName"].Value = strLastName;
cmd.Parameters.Add(new SqlParameter("#EmailAddress", SqlDbType.NVarChar, 50));
cmd.Parameters["#EmailAddress"].Value = strEmail;
cmd.Parameters.Add(new SqlParameter("#Address", SqlDbType.NVarChar, 150));
cmd.Parameters["#Address"].Value = strEmail;
//Return Value
cmd.Parameters.Add("#ReturnValue", SqlDbType.Int);
cmd.Parameters["#ReturnValue"].Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
intReturnValue = (int)cmd.Parameters["#ReturnValue"].Value;
strError = string.Empty;
}
catch (SqlException err)
{
intReturnValue = -1;
strError = err.Message;
}
catch (Exception ex)
{
intReturnValue = -1;
strError = ex.Message;
}
finally
{
objConn.Close();
}
}
else
{
//Error
intReturnValue = -1;
strError = "Error";
}
return intReturnValue;
}
Stored procedure "updateUserInfo":
USE [ATM]
GO
/****** Object: StoredProcedure [dbo].[updateUserInfo] Script Date: 4/15/2014 1:43:28 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[updateUserInfo]
#CardNum AS decimal,
#Username AS nvarchar(50),
#Password AS nvarchar(50),
#FirstName AS nvarchar(150),
#MiddleName AS nvarchar(150),
#LastName AS nvarchar(150),
#EmailAddress nvarchar(50),
#Address nvarchar(150)
AS
BEGIN TRY
BEGIN TRANSACTION
DECLARE #ReturnValue AS INT;
--Set current date
DECLARE #Date AS numeric(18,0);
DECLARE #Hours int;
DECLARE #Minutes int;
DECLARE #Seconds int;
DECLARE #Milliseconds INT;
DECLARE #CurDate as VARCHAR(50);
SET #Hours = DATEPART(hh, GETDATE())
SET #Minutes = DATEPART(mi, GETDATE())
SET #Seconds = DATEPART(ss, GETDATE())
SELECT #CurDate = CONVERT(VARCHAR(35),GETDATE(),112)
SET #CurDate = #CurDate + CONVERT(VARCHAR(5), #Hours) + CONVERT(VARCHAR(5), #Minutes) + CONVERT(VARCHAR(5),#Seconds)
SELECT #Date = CONVERT(decimal(18,0), #CurDate)
-- Insert statements for procedure here
enter code here
UPDATE dbo.tblClient
SET [cliCardNum] = #CardNum
,[cliFirstName] = #FirstName
,[cliMiddleName] = #MiddleName
,[cliLastName] = #LastName
,[cliEmailaddress] = #EmailAddress
,[cliAddress] = #Address
,[TimeStamp] = #Date
,Enabled = 1
WHERE cliUsername=#Username AND cliPassword=#Password
SET #ReturnValue=0;
COMMIT TRANSACTION;
RETURN #ReturnValue
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
ROLLBACK
-- Raise an error with the details of the exception
DECLARE #ErrMsg nvarchar(4000), #ErrSeverity int
SELECT #ErrMsg = ERROR_MESSAGE(),
#ErrSeverity = ERROR_SEVERITY()
RAISERROR(#ErrMsg, #ErrSeverity, 1)
SET #ReturnValue=-1;
Print #ReturnValue
RETURN #ReturnValue;
END CATCH
In my opinion the problem is on selecting the return value from within your stored procedure. I did a quick example in C# with a simple stored procedure.
// demo code to select the return value
string conStr = #"data source=*****; initial catalog=demoDb; integrated security=true";
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("declare #return_status int; exec #return_status = demoProcedure; select #return_status", con);
con.Open();
Console.WriteLine(com.ExecuteScalar());
con.Close();
My demo stored procedure
create PROCEDURE demoProcedure
AS
BEGIN
return 1;
END
GO
Found this example at Technet. I hope you can adapt my example to your code! If I did misunderstood your question or anything within my code is wrong - please let me know!
EDIT
While thinking about your problem I noted the following phrase on technet article
Exits unconditionally from a query or procedure. RETURN is immediate
and complete and can be used at any point to exit from a procedure,
batch, or statement block. Statements that follow RETURN are not
executed.
So when you would alter your procedure to select a value instead of returning it you could adapt your code to:
string conStr = #"data source=***; initial catalog=demoDb; integrated security=true";
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("demoProcedure", con);
com.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
Console.WriteLine(com.ExecuteScalar());
con.Close();
with a simple procedure
create PROCEDURE demoProcedure
AS
BEGIN
select 1;
END
EDIT 2
Your stored procedure returns 0 in case of success and -1 in case of a failure. But within your btnClick event your select stmt checks for 1 = success and 0 = failure. Please try changing your code to
protected void btnSubmit_Click(object sender, EventArgs e)
{
string display;
long cardnum;
string strcard = Request.Params.Get("__CREDITCARD");
if (long.TryParse(strcard, out cardnum))
{
// your code goes here ...
switch (retcode)
{
case 0: // changed to reflect returnValue from stored Procedure
// your code goes here ...
return;
case -1: // changed to reflect returnValue from stored Procedure
display = "Invalid credit card number";
break;
}
}
// your code goes here ...
}
I am the admin who wants to change the password for anyone by entering their email address and the new password in textbox.The stored procedure is as below:
Alter proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
as
begin
IF EXISTS (SELECT * FROM tblRegister WHERE Email=#Email)
begin
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
Select 0
end
ELSE
BEGIN
Select -1
end
end
and the code-behind is as below:
private void ChangePassword()
{
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
cmd.ExecuteNonQuery();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
ChangePassword();
}
But i want to check if the email exists in the table using if and else statements.If the email exists then change password else throw an exception.What can i do?
You could simply change a bit the code of your procedure and have it to return a value.
0 would mean that the password updated and -1 that there is not an email like the one provided.
ALTER proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
AS
BEGIN
IF EXISTS (SELECT * FROM Users WHERE Email=#Email) THEN
BEGIN
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
SELECT 0 AS Result
END
ELSE
BEGIN
SELECT -1 AS Result
END
END
Then you have to read the result of the stored procedure and act correspondingly. So your server side code must be changed to the following:
var reader = cmd.ExecuteReader();
while (reader.Read())
{
if(int.Parse(reader["Result"].ToString())==0)
{
// success
}
else
{
// failure
}
};
update In the if statement, you could also use this one:
Convert.ToInt32(reader["Result"])==0
I think it will work like a charm.
Inside your Stored procedure add this
Begin
DECLARE #id AS INT
SELECT #id = tblRegisterId FROM tblRegisterWHERE Email =#Email
IF #id IS not NULL
Begin
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
Select 1
End
Else
Begin
Select 0
End
End
Try this :-
private bool ChangePassword()
{
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
int count = cmd.ExecuteNonQuery();
if (count > 0)
return true;
else
return false;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
bool success = ChangePassword(); //Use this success variable to show a message.
}
You can also change your stored procedure, but it wont throw any exception, only it will check. If the Email exists, it will execute the update query :-
Create proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
as
begin
IF EXISTS ( SELECT * FROM tblRegister WHERE Email = #Email)
BEGIN
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
END
end
SQL
Create proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
as
begin
IF EXISTS ( SELECT * FROM tblRegister WHERE Email = #Email)
BEGIN
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
END
ELSE
BEGIN
RAISEERROR('Email does not exists',0,1)
END
end
c#
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
try{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
cmd.ExecuteNonQuery();
}
catch(SqlException ee)
{
...
}
}
Try this Store Procedure ( Please use IF EXISTS)
CREATE PROCEDURE InsertName
(
#Email varchar(25),
#Passwordd varchar(25)
)
AS
IF EXISTS(SELECT 'True' FROM tblRegister WHERE Email = #Email)
BEGIN
--This means it exists,update
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
SELECT 'Changed successfully'
END
ELSE
BEGIN
--This means the record isn't in there already
SELECT 'Does Not Exist'
END
private string ChangePassword()
{
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
return cmd.ExecuteNonQuery().ToString();
}
}
I've been searching the net for answers but have come up empty again and again.
What I'm trying to do:
Load the results from a stored procedure into a DataTable.
What's going wrong:
I'm not getting any rows returned.
Here is my stored proc (SQL Server 2012). It gets the next auto incremented ID of a table you input and returns it.
ALTER procedure [dbo].[GET_NEXT_AUTO_ID_OF_TABLE]
#TABLE_NAME nvarchar(128),
#NEXT_ID int output
as
declare #latest_id int, #row_count int
begin
set #latest_id = (select IDENT_CURRENT(#TABLE_NAME))
end
if #latest_id = 1
begin
declare #lRowCountSql nvarchar(1000)
set #lRowCountSql = N'select #row_count = count(*) from ' + #TABLE_NAME
exec sp_executesql #lRowCountSql, N'#row_count int out', #row_count out
if #row_count > 0
set #next_id = #latest_id + 1
else
set #next_id = #latest_id
end
else
set #next_id = #latest_id + 1
return
Is the problem my proc (I'm not good with sql)? When I test the proc in SQL Server I get the result I expect.
But not from my C# code:
List<SqlParameter> aSqlParams = new List<SqlParameter>();
aSqlParams.Add(new SqlParameter("#TABLE_NAME", "your table name") { Direction = System.Data.ParameterDirection.Input, SqlDbType = System.Data.SqlDbType.NVarChar });
aSqlParams.Add(new SqlParameter() { ParameterName = "#NEXT_ID", Direction = System.Data.ParameterDirection.Output, SqlDbType = SqlDbType.Int });
DataTable lDt = SQLServerUtils.ExecuteStoredProc("GET_NEXT_AUTO_ID_OF_TABLE", aSqlParams);
int lNextID = lDt.Rows[0].Field<int>("NEXT_ID");
public static DataTable ExecuteStoredProc(string aProcName, List<SqlParameter> aSqlParams)
{
DataTable lResults = new DataTable();
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(aProcName, conn);
cmd.CommandType = CommandType.StoredProcedure;
if (aSqlParams != null)
foreach (SqlParameter lP in aSqlParams)
cmd.Parameters.Add(lP);
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(lResults);
}
return lResults;
}
An output parameter is returned by itself, not included in a datatable.
I think you need a different procedure that executes these kind of query,
public static int ExecuteOutputIntParam(string aProcName, string outputParamName, List<SqlParameter> aSqlParams)
{
int outValue = -1;
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(aProcName, conn);
cmd.CommandType = CommandType.StoredProcedure;
if (aSqlParams != null)
foreach (SqlParameter lP in aSqlParams)
cmd.Parameters.Add(lP);
int result = cmd.ExecuteNonQuery();
if (aSqlParams != null)
{
outValue = Convert.ToInt32(aSqlParams[outputParamName].Value);
}
}
return outValue;
}
EDIT
I have copy/pasted your example and I haven't noticed that you rely on the SqlDataAdapter to open/close the connection. In my example the connection should be explicitly opened
The trick here is that the value I want comes back inside the out parameter.
The fixed code looks like this...
SQL proc:
ALTER procedure [dbo].[GET_NEXT_AUTO_ID_OF_TABLE]
#TABLE_NAME nvarchar(128),
#NEXT_ID int output
as
declare #latest_id int, #row_count int
begin
set #latest_id = (select IDENT_CURRENT(''+#TABLE_NAME+''))
end
if #latest_id = 1
begin
declare #lRowCountSql nvarchar(1000)
set #lRowCountSql = N'select #row_count = count(*) from ' + #TABLE_NAME
exec sp_executesql #lRowCountSql, N'#row_count int out', #row_count out
if #row_count > 0
set #next_id = #latest_id + 1
else
set #next_id = #latest_id
end
else
set #next_id = #latest_id + 1
return
C#:
public static int GetNextIdOfTable(string aTableName)
{
int lNextID = 0;
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand("GET_NEXT_AUTO_ID_OF_TABLE", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#TABLE_NAME", aTableName) { Direction = System.Data.ParameterDirection.Input, SqlDbType = System.Data.SqlDbType.NVarChar });
cmd.Parameters.Add(new SqlParameter() { ParameterName = "#NEXT_ID", Direction = System.Data.ParameterDirection.Output, SqlDbType = SqlDbType.Int });
conn.Open();
cmd.ExecuteReader();
if (cmd.Parameters["#NEXT_ID"] != null && cmd.Parameters["#NEXT_ID"].Value != DBNull.Value)
return int.Parse(cmd.Parameters["#NEXT_ID"].Value.ToString());
}
return lNextID;
}
In database:
Alter Procedure Update_MaterialTransactionsto2ForWithdrawal
#materialName varchar(50),
#staffNumber varchar(10),
#description varchar(50),
#transactionID int
As
Begin
Update Table_MaterialTransactions
set Status=2
where StaffNumber = #staffNumber
and CrossSection = #description
and SubSubCategory = #materialName
and Status = 1
and TransactionID = #transactionID
End
In data access layer:
public static void UpdateMaterial(string staffNumber,string materialName,string description,int transaction)
{
SqlConnection connection = new SqlConnection(ConnectDatabase.ReturnConnectionString());
//I am passing connection string as the parameter
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("Update_MaterialTransactionsto2ForWithdrawal", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.Add("#materialName", SqlDbType.Varchar, 50).Value = materialName;
cmd.Parameters.Add("#staffNumber", SqlDbType.Varchar, 50).Value = staffNumber;
cmd.Parameters.Add("#description", SqlDbType.Varchar, 50).Value = description;
cmd.Parameters.Add("#transactionID", SqlDbTypeInt).Value = transactionID;
int i = cmd.ExecuteNonQuery();
connection.Close();
}
catch(Exception ex)
{
connection.Close();
}
On the client side:
void btnSubmit_Click(Object sender,EventArgs e)
{
int j=0,k=0;
for(int i=0;i<transactions.Count;i++)
{
string id = "ctl00$ContentPlaceHolder1$" + i.ToString();
CheckBox chk=(CheckBox)Page.FindControl(id);
if(chk.Checked == true)
{
Objects.UpdateMaterial(staffNumbers[i].ToString(), materials[i].ToString(), descriptions[i].ToString(), Convert.ToInt32(transactions[i]));
j++;
}
else
{
Objects.DeleteTheSelectedRowOfMaterialTransaction(staffNumbers[i].ToString(), materials[i].ToString(), descriptions[i].ToString(), Convert.ToInt32(transactions[i]));
k++;
}
}
I have check boxes in the table and when the user checks the check boxes and clicks submit, the boxes which are checked will update the database.
But the cmd.ExecuteNonQuery() is not executing and it is returning 0 rows. It is not throwing any error. But if I do this manually in the database, the stored procedure is working fine.
Kindly tell me where I am going wrong.
try adding last line in procedure
Return ##Rowcount