I am trying to write a code do payment and update the status as well. In the following code I have done the logic to submit the payment which is working correctly but I am not able to update the status. Status is a column in Item_Order table which must get update after do the payment
My code is :
delegate void PaymentDone();
public void paySave()
{
SqlConnection conn1 = new SqlConnection();
try
{
conn1.ConnectionString = "
server=.\\ms2k5;database=Info_Connect;Trusted_Connection=true";
conn1.Open();
SqlCommand insertPayment = new SqlCommand("Delegate_SP", conn1);
insertPayment.CommandType = CommandType.StoredProcedure;
string currentDate = DateTime.Today.ToString();
if (Convert.ToDateTime(payDate.Text) >= Convert.ToDateTime(currentDate))
{
insertPayment.Parameters.Add("#reciptId", SqlDbType.VarChar);
insertPayment.Parameters["#reciptId"].Value = fullfill.Text;
insertPayment.Parameters.Add("#payDate", SqlDbType.DateTime);
insertPayment.Parameters["#payDate"].Value =
Convert.ToDateTime(payDate.Text);
insertPayment.Parameters.Add("#balPay", SqlDbType.Float);
insertPayment.Parameters["#balPay"].Value = Convert.ToDouble(balace.Text) - Convert.ToDouble(amnt1.Text);
insertPayment.Parameters.Add("#payDone", SqlDbType.Float);
insertPayment.Parameters["#payDone"].Value =
Convert.ToDouble(amnt1.Text);
insertPayment.Parameters.Add("#fullfillID_FK", SqlDbType.VarChar);
insertPayment.Parameters["#fullfillID_FK"].Value = fullfill.Text;
insertPayment.Parameters.Add("#clintID_FK", SqlDbType.Int);
insertPayment.Parameters["#clintID_FK"].Value =
(clintId_FK.Text).ToString();
insertPayment.Parameters.Add("#operation", SqlDbType.VarChar);
insertPayment.Parameters["#operation"].Value = 3;
insertPayment.ExecuteNonQuery();
}
else
{
MessageBox.Show("Payment Date Should be later than Full Order Date");
}
}
}
public void payUpdate()
{
SqlConnection conn1 = new SqlConnection();
try
{
conn1.ConnectionString = "
server=.\\ms2k5;database=Info_Connect;Trusted_Connection=true";
conn1.Open();
SqlCommand insertStaus = new SqlCommand("Delegate_SP", conn1);
insertStaus.CommandType = CommandType.StoredProcedure;
insertStaus.Parameters.Add("#status", SqlDbType.VarChar);
insertStaus.Parameters["#status"].Value = "RUNING";
if (balace.Text.Equals("0"))
{
insertStaus.Parameters.Add("#status", SqlDbType.VarChar);
insertStaus.Parameters["#status"].Value = "CLOSE";
}
else
{
insertStaus.Parameters.Add("#status", SqlDbType.VarChar);
insertStaus.Parameters["#status"].Value = "RUNING";
}
MessageBox.Show("3");
insertStaus.Parameters.Add("#operation", SqlDbType.VarChar);
insertStaus.Parameters["#operation"].Value = 2;
insertStaus.ExecuteNonQuery();
}
}
And my stored procedure is
ALTER PROCEDURE [dbo].[Delegate_SP]
#reciptId varchar(50)=null,
#balPay float,
#payDone float=null,
#payDate datetime=null,
#fullfillId_FK varchar(50)=null,
#clintId_FK int=null,
#status varchar(50)=null,
#operation int,
#fullfillId varchar(50)=null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
if #operation=3
BEGIN
UPDATE Recipt set balPay=#balPay where reciptId=#reciptId
if ##rowcount=0
insert into Recipt(reciptId,balPay,payDone,payDate,fullfillId_FK,clintId_FK)values
(#reciptId,#balPay,#payDone,#payDate,#fullfillId_FK,#clintId_FK)
update Item_Full set totCost=(select balPay from Recipt) where fullfillId=#reciptId
END
if #operation=2
BEGIN
UPDATE Item_Order set status=#status where orderId=#reciptId
END
END
the problem is that I got tdsparser exception in payUpdate method... the paySave method is working correctly
Related
I have three columns
Fraquence int
[Prochain étalonnag] date
[date étalonnage] type:date
In Visual Studio, I have a form for adding a new (etalonnage) to my table the user inputs two vules (Fraquence and date étalonnage).
I want to do this with a stored procedure in SQL Server :
Prochain étalonnag = date étalonnage + (Month Fraquence).
The column Prochain étalonnage will be filled automatically when the user click in button Add.
Please check following .NET code, sorry it is in VB.NET
But it is not a problem to convert it to C#
The stored procedure in database is named prAddRow for this sample
It accepts two parameters #p_int and #p_date
Dim sqlConnBuilder As New SqlConnectionStringBuilder()
sqlConnBuilder.DataSource = txtSQLServer.Text
sqlConnBuilder.InitialCatalog = txtDatabase.Text
sqlConnBuilder.IntegratedSecurity = True
conn = New SqlConnection(sqlConnBuilder.ToString)
Dim cmd As New SqlCommand("prAddRow")
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#p_int", SqlDbType.Int).Value = 1
cmd.Parameters.Add("#p_date", SqlDbType.Date).Value = Date.Now.Date
conn.Open()
cmd.Connection = conn
Dim numberOfAffectedRows As Integer = cmd.ExecuteNonQuery()
conn.Close()
The T-SQL source codes for the sample stored procedure is as follows
create procedure prAddRow(
#p_int int,
#p_date date
)
as
insert into etalonnage (Fraquence , [date etalonnage] ) values (#p_int, #p_date)
go
Note: I renamed stored procedure according to marc's note from sp_addRow to prAddRow
I hope it is useful for you
private void button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("INSERTNEW", connection);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter [] par = new SqlParameter[4];
par[0] = new SqlParameter("#COD", SqlDbType.VarChar, 50);
par[0].Value = textBox1.Text;
par[1] = new SqlParameter("#FERQ", SqlDbType.Int);
par[1].Value = numericUpDown1.TextAlign;
par[2] = new SqlParameter("#DATE_ET", SqlDbType.Date);
par[2].Value = dateTimePicker1.Text;
par[3] = new SqlParameter("#DATE_PROC", SqlDbType.Date);
DateTime d1 = Convert.ToDateTime(dateTimePicker1.Text);
int k =Convert.ToInt32(numericUpDown1.TextAlign);
string r = d1.AddMonths(k).ToShortDateString();
par[3].Value = r ;
cmd.Parameters.AddRange(par);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show("good add");
}
this is work thanks all
Currently, my program in Visual Studio dynamically adds my data from my Repeater into my database.
Now I need to add the ID, my EventId and FormId, which I collected manually outside of the Repeater.
I need to add this in:
sqlCmd.Parameters.Add("#EventId", SqlDbType.Int).Value = eventId;
sqlCmd.Parameters.Add("#FormId", SqlDbType.Int).Value = formId;
However with how my code is setup, it gives an error when I add this code that says:
Additional information: Procedure or function 'spInsFormRegistrant'
expects parameter '#EventId', which was not supplied.
Working code (with error code commented out):
protected void BtnSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
{
sqlConn.Open();
using (SqlCommand sqlCmd = new SqlCommand())
{
//sqlCmd.Parameters.Add("#EventId", SqlDbType.Int).Value = eventId;
//sqlCmd.Parameters.Add("#FormId", SqlDbType.Int).Value = formId;
foreach (RepeaterItem rpItem in RepeaterForm.Items)
{
Label lblDisplayName = rpItem.FindControl("lblDisplayName") as Label;
Label lblColumnName = rpItem.FindControl("lblColumnName") as Label;
TextBox txtColumnValue = rpItem.FindControl("txtColumnValue") as TextBox;
if (txtColumnValue != null)
{
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "spInsFormRegistrant";
sqlCmd.Parameters.Clear();
sqlCmd.Parameters.Add("#ColumnName", SqlDbType.NVarChar).Value = lblColumnName.Text;
sqlCmd.Parameters.Add("#ColumnValue", SqlDbType.NVarChar).Value = txtColumnValue.Text;
sqlCmd.ExecuteNonQuery();
}
}
}
}
PnlNone.Visible = false;
PnlExist.Visible = false;
PnlSuccess.Visible = true;
PnlFail.Visible = false;
}
So I just need to know where to add in #EventId and #FormId for this to function correctly. Each time I try it, it does not work. I must be missing something small for this to not produce an error. Or maybe it is an issue with my stored procedure...?
Stored Procedure
ALTER PROCEDURE [dbo].[spInsFormRegistrant]
-- Add the parameters for the stored procedure here
#EventId int,
#FormId int,
#ColumnName varchar(100),
#ColumnValue varchar(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
declare #Query nvarchar(4000)
declare #ParmDefinition nvarchar(500);
set #Query = 'INSERT into Registrant(DateCreated,EventId,FormId,'+ (#ColumnName) +') values (CURRENT_TIMESTAMP, #EventId, #FormId, #ColumnValue)'
set #ParmDefinition = N'#ColumnValue varchar(100)'
exec sp_executesql #Query, #ParmDefinition, #ColumnValue = #ColumnValue
END
You are not adding the parameter for eventID and for FormID, but you should try to use a different approach. Do not create everytime the parameters. You could create them just one time before entering the foreach loop and then, inside the loop change only their value
// This part never changes so, set it up just one time before the loop
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "spInsFormRegistrant";
sqlCmd.Parameters.Add("#EventId", SqlDbType.Int).Value = eventId;
sqlCmd.Parameters.Add("#FormId", SqlDbType.Int).Value = formId;
// These twos change inside the loop, so we don't need the value here
sqlCmd.Parameters.Add("#ColumnName", SqlDbType.NVarChar);
sqlCmd.Parameters.Add("#ColumnValue", SqlDbType.NVarChar);
foreach (RepeaterItem rpItem in RepeaterForm.Items)
{
Label lblDisplayName = rpItem.FindControl("lblDisplayName") as Label;
Label lblColumnName = rpItem.FindControl("lblColumnName") as Label;
TextBox txtColumnValue = rpItem.FindControl("txtColumnValue") as TextBox;
if (txtColumnValue != null)
{
sqlCmd.Parameters["#ColumnName"].Value = lblColumnName.Text;
sqlCmd.Parameters["#ColumnValue"].Value = txtColumnValue.Text;
sqlCmd.ExecuteNonQuery();
}
}
Of course you don't need the call to Parameters.Clear
Then there is a problem in the way in which you pass the paramenters to the sp_executesql call inside the stored procedure. That system storedprocedure requires that you set the datatype for every parameter used in the query and an initialization list of these parameters.
You should write
...
-- Insert statements for procedure here
declare #Query nvarchar(4000)
declare #ParmDefinition nvarchar(500);
set #Query = 'INSERT into Registrant(DateCreated,EventId,FormId,'+
(#ColumnName) +') values (CURRENT_TIMESTAMP, #EventId, #FormId, #ColumnValue)'
set #ParmDefinition = N'#ColumnValue varchar(100), #EventID int, #FormID int'
exec sp_executesql #Query, #ParmDefinition,
#ColumnValue = #ColumnValue,
#EventID = #EventID,
#FormID = #FormID
You are clearing the parameters:
sqlCmd.Parameters.Clear();
You need to add them over and over:
foreach (RepeaterItem rpItem in RepeaterForm.Items)
{
Label lblDisplayName = rpItem.FindControl("lblDisplayName") as Label;
Label lblColumnName = rpItem.FindControl("lblColumnName") as Label;
TextBox txtColumnValue = rpItem.FindControl("txtColumnValue") as TextBox;
if (txtColumnValue != null)
{
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "spInsFormRegistrant";
sqlCmd.Parameters.Clear(); //that's fine, keep it
//just put them in here
sqlCmd.Parameters.Add("#EventId", SqlDbType.Int).Value = eventId;
sqlCmd.Parameters.Add("#FormId", SqlDbType.Int).Value = formId;
sqlCmd.Parameters.Add("#ColumnName", SqlDbType.NVarChar).Value = lblColumnName.Text;
sqlCmd.Parameters.Add("#ColumnValue", SqlDbType.NVarChar).Value = txtColumnValue.Text;
sqlCmd.ExecuteNonQuery();
}
}
I apologise for this formatting. I am new to programming and new to this site, so I will try and make the question as clear as possible.
I have a webform for accessing/modifying a Customer database. I have a button for entering new customers details which will automatically assign an ID number by getting the highest ID number from the database, and incrementing by one (and posting to form textbox).
This is the code I have written:
protected void btnNew_Click(object sender, EventArgs e)
{
Clear();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "NewCustomer";
conn.Open();
SqlParameter maxid = new SqlParameter();
maxid.ParameterName = "#MaxID";
maxid.SqlDbType = SqlDbType.Int;
maxid.Direction = ParameterDirection.Output;
command.Parameters.Add(maxid);
command.ExecuteNonQuery();
NewCustId = Convert.ToInt32(maxid.Value);
NewCustId += 1;
txtCustID.Text = (NewCustId).ToString();
txtCustID.DataBind();
conn.Close();
}
This is the stored procedure:
CREATE PROCEDURE NewCustomer
(#MaxID INT OUTPUT)
AS
BEGIN
SELECT #MaxID = MAX(CustID)
FROM dbo.Customer
END
I have tried many different ways of coding it, but nothing seems to work.
The code I have posted has an exception at ExecuteNonQuery saying arguments were supplied and procedure has no parameters. When I place command.Parameters.Add(maxid); underneath ExecuteNonQuery, it returns a 1.
I ran the SQL Query alone to see what would happen and it returns a correct answer in an unnamed cell. For some reason the Column Name disappears when it comes up. Then when I try to use the C# code to access the unnamed cell, I can't seem to access it because the column 'CustID' "doesn't exist".
With this code, I know that the SQL command is executing, and then the C# code increments by 1, but it seems that the return value I am getting is 0.
I appreciated any ideas that I can get on how to fix this. Thank you.
Edit: I have also tried:
DataTable table = new DataTable();
adapter.Fill(table);
NewCustId = table.Rows[0].Field("CustID");
(This is where it said 'CustID' column didn't exist)
Change your code to the following and try again:
Clear();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "NewCustomer";
conn.Open();
NewCustId = Convert.ToInt32(cmd.ExecuteScalar().ToString());
NewCustId += 1;
txtCustID.Text = NewCustId.ToString();
conn.Close();
And your stored procedure is:
CREATE PROCEDURE NewCustomer
(
)
AS
BEGIN
SELECT MAX(CustID)
FROM dbo.Customer;
END
ExecuteNonQuery() expects no results. Try ExecuteReader() instead.
I second what marc_S is saying about this running into issues.
Since you are using max ID and incrementing by 1 to insert a new record in the database, I suggest that you use Identity(seed, increment_value) for this column.
That way you don't have to find max to insert a new record and you avoid lots of transaction issues.
Once the transaction is done
Possible Design:
Create Table Customer
(
Id Int Identity(1,1),
Name varchar(50)
)
Create Proc NewCustomer
(
#Name varchar(50)
)
As
(
DECLARE #custID Int
SET NOCOUNT ON
INSERT INTO Customer (Name) Values('Your Name')
SET #custID = SCOPE_IDENTITY()
RETURN #custID
)
protected void btnNew_Click(object sender, EventArgs e)
{
Clear();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "NewCustomer";
conn.Open();
SqlParameter name = new SqlParameter();
name.ParameterName = "#Name";
name.Direction = ParameterDirection.Input;
name.SqlDbType = SqlDbType.Varchar;
name.Value = "Your Name";
command.Parameters.Add(name);
SqlParameter returnValue= new SqlParameter();
returnValue.ParameterName = "#custID";
returnValue.SqlDbType = SqlDbType.Int;
returnValue.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(maxid);
command.ExecuteNonQuery();
NewCustId = Convert.ToInt32(returnValue.Value);
txtCustID.Text = (NewCustId).ToString();
txtCustID.DataBind();
conn.Close();
}
CREATE TABLE MYUSE100(userid number,username varchar2(45),ppassword varchar2(50));
insert into MYUSE200 values('harry','potter');
here is my stored procedure
create or replace procedure p_myuse200(p_username1 in varchar2,p_password1 in varchar2,v_count out number)
AS
BEGIN
select count(*) INTO v_count from MYUSE200 where username1=p_username1 and password1=p_password1;
IF v_count>0 THEN
v_count:=v_count+0;
ELSE
v_count:=0;
END IF;
END;
/
codebehind
protected void button1_onclick(object sender, EventArgs e)
{
OracleConnection conn = new OracleConnection(strConnString);
OracleCommand cmd = new OracleCommand("p_myuse200",conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
OracleParameter username1 = new OracleParameter("p_username1", OracleDbType.Varchar2, 50);
username1.Value = textbox1.Text;
cmd.Parameters.Add(username1);
OracleParameter password1 = new OracleParameter("p_password1 ", OracleDbType.Varchar2, 45);
password1.Value = textbox2.Text;
cmd.Parameters.Add(password1);
cmd.Parameters.Add("v_count", OracleDbType.Varchar2, 30);
cmd.Parameters["v_count"].Direction = ParameterDirection.Output;
Int32 results = 0;
//results = (Int32)cmd.Parameters["v_count"].Value;
try
{
results = Convert.ToInt32(cmd.Parameters["values"].Value);
cmd.ExecuteScalar();
//cmd.ExecuteNonQuery();
if (results > 0)
{
Response.Redirect("http://www.google.com");
}
else
{
Response.Redirect("http://www.facebook.com");
}
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
Response.Redirect("http://www.gmail.com");
}
}
}
I'm unable to login any suggestions, both in case of stored procedure and codebehind.
results>0 is not getting the current value count=1 and results should be 1 but it is always zero and else block is executing,,,
ExecuteScalar executes the query, and returns the first column of the first row in the result set returned by the query. You should get the results from the query like this:
var results = (int) ExecuteScalar();
I have the following stored proc that is throwing the aforementioned exception when I call it in a winform. The purpose of this form is to generate a number of randomized codes, format them, and store them in a database:
ALTER procedure [dbo].[StoredProc] (
#unimporantParam1 int,
#unimporantParam2 varchar(14),
#variableInQuestion varchar(10) OUT
)
As
Begin
exec dbo.GenerateRandomString 1,1,0,null,10,#variableInQuestion OUT
INSERT INTO [dbo].[sproc_table]
([unimportant_column1]
,[column_in_question]
,[unimportant_column2]
,[unimportant_column3]
,[unimportant_comlumn4])
SELECT #unimportantParam1
,(SELECT SUBSTRING(#variableInQuestion, 1, 3) + '-'
+ SUBSTRING(#variableInQuestion, 4, 4) + '-'
+ SUBSTRING(#variableInQuestion, 8, 3))
,GETDATE()
,0
,#unimportantVariable2
END
Being called by this C#:
private void btnGenerate_Click(object sender, EventArgs e)
{
int i;
var numberOfCodes = int.Parse(txtCodes.Text);
for (i = 1; i <= numberOfCodes; i++)
{
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
conn.Open();
try
{
var command = new SqlCommand("StoredProc", conn)
{
CommandType = CommandType.StoredProcedure
};
command.Parameters.Add(new SqlParameter("#unimportantParam1", SqlDbType.Int, 0, "param1"));
command.Parameters.Add(new SqlParameter("#unimportantParam2", SqlDbType.VarChar, 14, "param2"));
command.Parameters[0].Value = txtUnimportant1.Text;
command.Parameters[1].Value = txtUnimportant2.Text;
command.ExecuteNonQuery();
}
finally
{
conn.Close();
conn.Dispose();
}
}
}
When I test it in SQL Server, it does what its supposed to, but when I test through the C# code, I get the above error. Can anyone tell me what I'm doing wrong with the substring formatting or if its something else causing the error. I appreciate any help that can be given.
When you create the variableInQuestion in your winForm you have to set it as a parameter without seeing your c# code I am assuming you have not done this, to do this the code looks like the following:
SqlParameter param = new SqlParameter();
SqlCommand cmd = new sqlCommand();
param = cmd.Parameters.Add("#variableInQuestion", SqlDbType.VarChar);
param.Direction = ParameterDirection.ReturnValue;
after when you execute your stored procedure it will store the returned value in the command
and you can access it using:
String someString = cmd.Parameters["#variableInQuestion"].Value.ToString();