I am receiving the error, Must declare the scalar variable "#ID". Pointing at ExecuteScalar line. I looked on goggle and I think it has something to do with insert parameters for ID. Then again I read there could be a typo error. In my db I have declare column name as ID and Data Type as int, setting 'Is Identity' as Yes. As I am not going to insert ID column manually I think this is why I am having problem(s) and I don't know how to solve this problem.
What I am trying to do is insert username, login date and time. Update on the same column (same id column) when user logs out. Create a new column when user log in again and So on. I am using the similar code that I asked here and here when D Stanley helped me.
Thanks in advance if anyone can help me.
private int ID // forgot to add this.
{ get; set; }
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
string value = cbRoles.Text;
switch (value)
{
case "Manager":
myCon.connectionString();
string dString = string.Empty;
SqlConnection thisConnection = myCon.dbCon;
SqlCommand nonqueryCommand = thisConnection.CreateCommand();
using (var command = myCon.dbCon.CreateCommand())
{
command.CommandText = "SELECT * FROM tblPrivileges";
command.Parameters.AddWithValue("UserName", (txtUserName.Text));
command.Parameters.AddWithValue("Password", (txtPassword.Text));
thisConnection.Open();
var reader = command.ExecuteReader(); //strcomp
{
if (reader.HasRows)
{
while (reader.Read())
{
txtUserName.Text = reader["UserName"].ToString();
txtPassword.Text = reader["Password"].ToString();
MainWindow gobackB = new MainWindow();
gobackB.Show();
LoginSample goback = new LoginSample();
goback.Hide();
}
}
else MessageBox.Show("You have entered incorrect credentials. Please try again", "error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
myCon.dbCon.Close();
nonqueryCommand.CommandType = CommandType.Text;
nonqueryCommand.CommandText = "INSERT tblLoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (#UserName, #LoggedInDate, #LoggedInTime)";
//nonqueryCommand.Parameters.AddWithValue("#ID", SqlDbType.Int); this did not work
//nonqueryCommand.Parameters["#ID"].Value = this.ID; this did not work
nonqueryCommand.Parameters.AddWithValue("#UserName", txtUserName.Text);
nonqueryCommand.Parameters.AddWithValue("#LoggedInDate", DateTime.Now);
nonqueryCommand.Parameters.AddWithValue("#LoggedInTime", DateTime.Now.ToString("HH:mm"));
thisConnection.Open();
nonqueryCommand.ExecuteNonQuery(); // error pointing here
nonqueryCommand.CommandText = "SELECT #ID = SCOPE_IDENTITY()";
int id = (int)nonqueryCommand.ExecuteScalar();
// int id = Convert.ToInt32(nonqueryCommand.ExecuteScalar()); this line did not work
this.ID = id;
myCon.dbCon.Close();
break;
The problem is still that you're trying to use the same "scope" with two different SQL commands. Even thought they are the same "variable" in C# in SQL they have different scope.
You'll need to execute both statements in one command and add the #ID parameter as an Output parameter in order to insert and get the identity out:
nonqueryCommand.CommandType = CommandType.Text;
nonqueryCommand.CommandText = "INSERT tblLoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (#UserName, #LoggedInDate, #LoggedInTime); " +
"SELECT #ID = SCOPE_IDENTITY()";
nonqueryCommand.Parameters.AddWithValue("#UserName", txtUserName.Text);
nonqueryCommand.Parameters.AddWithValue("#LoggedInDate", DateTime.Now);
nonqueryCommand.Parameters.AddWithValue("#LoggedInTime", DateTime.Now);
nonqueryCommand.Parameters.Add("#ID",SqlDbType.Int).Direction = ParameterDirection.Output;
thisConnection.Open();
nonqueryCommand.ExecuteNonQuery();
int id = (int)nonqueryCommand.Parameters["#ID"];
Here:
nonqueryCommand.CommandText = "SELECT #ID = SCOPE_IDENTITY()";
your SQL assigns a value to a variable that is not declared. Since you are using ExecuteScalar, you probably just mean:
nonqueryCommand.CommandText = "SELECT SCOPE_IDENTITY()";
Note that you might need to cast it - it may come back as decimal.
Related
When i run my code in the debugger and I hover my mouse over the parameters they do have the right values in them. It just doesn't update my database but when I copy the query and put it into the database it works without a problem.
The parameter values are:
id = 7
omschrijving = douche muntjes
prijs = 0,5
catagorie = faciliteiten
I checked the connection tring by using an insert query and that does add records to my database. And There is an id with the value of 7 in the database.
When I run a insert query or a delete query through my C# code it does work it's just the update statement that doesn't work. If anyone sees the issue please help me.
public static void wijzigprijs(int id, string omschrijving, decimal prijs, string catagorie)
{
try
{
try
{
OleDbConnection verbinding = new OleDbConnection(
#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=..\..\..\La_Rustique.accdb;
Persist Security Info=False;");
verbinding.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
OleDbCommand query = new OleDbCommand();
query.CommandText = #"UPDATE prijslijst
SET omschrijving = #omschrijving,
prijs = #prijs,
catagorie = #catagorie
WHERE id = #id";
query.Parameters.Add(new OleDbParameter("#id", OleDbType.Integer));
query.Parameters["#id"].Value = id;
query.Parameters.Add(new OleDbParameter("#omschrijving", OleDbType.VarChar));
query.Parameters["#omschrijving"].Value = omschrijving;
query.Parameters.Add(new OleDbParameter("#prijs", OleDbType.Decimal));
query.Parameters["#prijs"].Value = prijs;
query.Parameters.Add(new OleDbParameter("#catagorie", OleDbType.VarChar));
query.Parameters["#catagorie"].Value = catagorie;
query.Connection = verbinding;
query.ExecuteNonQuery();
MessageBox.Show("succesvol gewijzigd");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
verbinding.Close();
}
}
EDIT UPDATE
Look at this topic. Here he explains how you should use variables with OleDbCommand
Variables with OleDbCommand
This is how you typically will do it when using SQLCommand parameters:
I know this doesnt answer your questions quite, but when i use SQLCommand i use this code whenever i want to update or insert with variables:
string query = #"UPDATE prijslijst
SET omschrijving = #omschrijving,
prijs = #prijs,
catagorie = #catagorie
WHERE id = #id";
SqlCommand cmd = new SqlCommand(query, connDatabase);
cmd.Parameters.Add("#id", SqlDbType.integer).Value = 7;
cmd.ExecuteNonQuery();
connDatabase.Close();
So you should be able to do the samething. Hope this will help you.
I have never seen OleDB queries written in the above syntax.
To state it differently: OleDB simply does not use named parameters, it uses the position only.
Try to change your SQL statement like this:
query.CommandText = #"UPDATE prijslijst
SET omschrijving = ?,
prijs = ?,
catagorie = ?
WHERE id = ?";
and then add the parameters in sequence of above in the code
below that.
I am working on an invoice managament application that draws information from an Access database (modern .accdb format) and getting the data works fine, but when I try to update it (following some tutorials, or should I say answers, nothing works..
What is wrong with this code, it... should work.
public int UpdateDBBill(Bill bill)
{
using (var connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\BC.accdb"))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE Bills SET Payer = #Payer, Category = #Category, Recipient = #Recipient, Currency = #Currency, Amount = #Amount, IBANOfRecipient = #IBANOfRecipient, Model = #Model, ReferenceNumber = #ReferenceNumber, Description = #Description, DueDate = #DueDate, ForMonth = #ForMonth, Paid = #Paid, DatePaid = #DatePaid WHERE Id = #Id";
command.Parameters.AddWithValue("#Payer", bill.Payer);
command.Parameters.AddWithValue("#Category", bill.Category);
command.Parameters.AddWithValue("#Recipient", bill.Recipient);
command.Parameters.AddWithValue("#Currency", bill.Currency);
command.Parameters.AddWithValue("#Amount", bill.amount);
command.Parameters.AddWithValue("#IBANOfRecipient", bill.IBANOfRecipient);
command.Parameters.AddWithValue("#Model", bill.Model);
command.Parameters.AddWithValue("#ReferenceNumber", bill.ReferenceNumber);
command.Parameters.AddWithValue("#Description", bill.Description);
command.Parameters.AddWithValue("#DueDate", bill.DueDate);
command.Parameters.AddWithValue("#ForMonth", bill.ForMonth);
command.Parameters.AddWithValue("#Paid", bill.Paid);
command.Parameters.AddWithValue("#DatePaid", bill.DatePaid);
command.Parameters.AddWithValue("#Id", bill.Id);
try
{
return command.ExecuteNonQuery();
}
catch
{
return -1;//for error
}
}
}
Answer:
public int UpdateDBBill(Bill bill)
{
using (var connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\BC.accdb"))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE Bills SET Payer = #Payer, Category = #Category, Recipient = #Recipient, [Currency] = #Currency, Amount = #Amount, IBANOfRecipient = #IBANOfRecipient, [Model] = #Model, ReferenceNumber = #ReferenceNumber, DueDate = #DueDate, ForMonth = #ForMonth, Paid = #Paid, DatePaid = #DatePaid WHERE Id = #Id";
command.Parameters.Add("#Payer", OleDbType.VarChar).Value = bill.Payer;
command.Parameters.Add("#Category", OleDbType.VarChar).Value = bill.Category;
command.Parameters.Add("#Recipient", OleDbType.VarChar).Value = bill.Recipient;
command.Parameters.Add("#Currency", OleDbType.VarChar).Value = bill.Currency;
command.Parameters.Add("#Amount", OleDbType.VarChar).Value = bill.GetAmount();
command.Parameters.Add("#IBANOfRecipient", OleDbType.VarChar).Value = bill.IBANOfRecipient;
command.Parameters.Add("#Model", OleDbType.VarChar).Value = bill.Model;
command.Parameters.Add("#ReferenceNumber", OleDbType.VarChar).Value = bill.ReferenceNumber;
command.Parameters.Add("#DueDate", OleDbType.Date).Value = bill.DueDate.Date;
command.Parameters.Add("#ForMonth", OleDbType.Date).Value = bill.ForMonth.Date;
command.Parameters.Add("#Paid", OleDbType.Boolean).Value = bill.Paid;
command.Parameters.Add("#DatePaid", OleDbType.Date).Value = bill.DatePaid.Date;
command.Parameters.Add("#Id", OleDbType.Integer).Value = bill.Id;
try
{
int Rows = command.ExecuteNonQuery();
return Rows;
}
catch
{
return -1;//for error
}
}
}
With OleDb the position of the parameters matters a lot.
OleDb doesn't associate parameters' placeholders with the parameters' names but follows a strictly positional order. So, your query is correct, but when you add the parameters to the collection you should follow the parameter placeholders order.
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE Bills SET ([Payer] = #Payer, [Category] = #Category, ...) WHERE Id = #Id";
command.Parameters.AddWithValue("#Payer", bill.Payer);
command.Parameters.AddWithValue("#Category", bill.Category);
....
command.Parameters.AddWithValue("#Id", bill.Id);
With Access you can name your parameters as you do for its big cousin Sql Server albeit the OleDb docs say that you should use the question mark as parameter placeholder, however the names are simply ignored when the OleDb provider associates the values to the placeholders.
As a side note, consider that AddWithValue is an handy but dangerous method. The parameter type is extracted by the value passed and sometimes this could create a 'DataType mismatch Exception' or wrong conversions (in particular if you pass dates or decimals as strings to AddWithValue)
See Can we stop using AddWithValue already?
EDIT After a long debug session in chat the final problem is identified in the Currency field written withot brackets. Currency is a reserved words in Access and should be enclosed in square bracket. This was not initially evident because the first query proposed by the OP was correctly typed with square bracket but then the square brackets disappeared from the query for whatever reason. The suggestion to NOT use AddWithValue stands to avoid unnecessary conversions from dates to strings and then back to strings....
command.CommandText = "UPDATE Bills SET ([Payer] = #Payer, [Category] = #Category, ...) WHERE Id = #Id";
command.Parameters.Add("#Payer", OleDbType.VarWChar).Value = bill.Payer;
command.Parameters.Add("#Category", OleDbType.VarWChar).Value = bill.Category;
....
command.Parameters.Add("#DueDate", OleDbType.Date).Value = bill.DueDate.Date;
....
command.Parameters.Add("#Id", OleDbType.Integer).Value = bill.Id;
I came across with this before. My issue was, I was not providing the parameters in the order they were present in the query.
In your case, as your update goes on with parameters Payer, Category...,Id your AddWithValues should follow the same order.
I hope this helps
Ok... I found the issue.
First of all, you should put the Currency field in brackets because Access considers it as a datatype if you don't and you get Syntax error.
Then, keep all AddWithValue statements order untouched.
Finally, while adding date fields (DueDate, ForMonth and DatePaid), use ToString("yyyy-MM-dd") so that Access will interpret the value as date. Also, parse the amount field to double.
Below is my version of the code. Hope this will work :)
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE Bills SET Payer = #Payer, Category = #Category, Recipient = #Recipient, [Currency] = #Currency, Amount = #Amount, IBANOfRecipient = #IBANOfRecipient, Model = #Model, ReferenceNumber = #ReferenceNumber, Description = #Description, DueDate = #DueDate, ForMonth = #ForMonth, Paid = #Paid, DatePaid = #DatePaid WHERE Id = #Id";
command.Parameters.AddWithValue("#Payer", bill.Payer);
command.Parameters.AddWithValue("#Category", bill.Category);
command.Parameters.AddWithValue("#Recipient", bill.Recipient);
command.Parameters.AddWithValue("#Currency", bill.Currency);
command.Parameters.AddWithValue("#Amount", Convert.ToDouble(bill.amount));
command.Parameters.AddWithValue("#IBANOfRecipient", bill.IBANOfRecipient);
command.Parameters.AddWithValue("#Model", bill.Model);
command.Parameters.AddWithValue("#ReferenceNumber", bill.ReferenceNumber);
command.Parameters.AddWithValue("#Description", bill.Description);
command.Parameters.AddWithValue("#DueDate", bill.DueDate.ToString("yyyy-MM-dd"));
command.Parameters.AddWithValue("#ForMonth", bill.ForMonth.ToString("yyyy-MM-dd"));
command.Parameters.AddWithValue("#Paid", bill.Paid);
command.Parameters.AddWithValue("#DatePaid", bill.DatePaid.ToString("yyyy-MM-dd"));
command.Parameters.AddWithValue("#Id", bill.Id);
try
{
return command.ExecuteNonQuery();
}
catch
{
return -1;//for error
}
I want to get the value to insert a table in C#,something like this:
begin
insert into bk_library(floor,section) values('foo2','bar')
returning id into :outid;
select *from bk_library where id=:outid;
end;
Unfortunately, I failed
error info: Kiss.Linq.Linq2Sql.Test.EntryPoint.TestInsertReturnId:
Oracle.DataAccess.Client.OracleException : ORA-06550: line 3, column
1: PLS-00428: an INTO clause is expected in this SELECT statement
[Test]
public void TestInsertReturnId()
{
int ret = 0;
string connstring = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=pdborcl)));User Id=system;Password=****;";
string sql = #"insert into bk_library(floor,section) values('foo','bar') returning id into :outid";
sql = getSqlString();
using (DbConnection conn = new OracleConnection(connstring))
{
conn.Open();
DbCommand command = conn.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
OracleParameter lastId = new OracleParameter(":outid", OracleDbType.Int32);
lastId.Direction = ParameterDirection.Output;
command.Parameters.Add(lastId);
ret = command.ExecuteNonQuery();
// this code work fine ,now I want to get the entire record
LogManager.GetLogger<EntryPoint>().Info("The new id ={0}", lastId.Value.ToString());
conn.Close();
}
Assert.AreNotEqual(ret, 0);
}
ParameterDirection should be ReturnValue
lastId.Direction = ParameterDirection.ReturnValue;
From < http://arjudba.blogspot.ch/2008/07/pls-00428-into-clause-is-expected-in.html?m=1>
You need to write SELECT * INTO some_variable FROM bk_library instead of SELECT * FROM bk_library because I assume you want to store the data retrieved somehow. Therefore you need to declare a new variable some_variable (I assume of type string) and modify your SELECT statement as above. The data from the statement will then be stored in your new variable.
Hope this helps
I have inserted values into sql several times but now i am facing problem with the following code
protected void Button1_Click(object sender, EventArgs e)
{
string connstring = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
con = new SqlConnection(connstring);
string name = txtName.Text;
string user = txtUser.Text;
string password = txtPwd.Text;
string email = txtEmail.Text;
long phone=Convert.ToInt64(txtPhone.Text);
string address = txtAddr.Text;
string city = txtCity.Text;
string gender = RadioButtonList1.SelectedItem.ToString();
string dob = txtDOB.Text;
string qualification = DropDownList1.SelectedItem.ToString();
string skills = CheckBoxList1.SelectedItem.ToString();
string insertstring = " insert into JobRegisteration values ("+name+","+user+","+password+","+email+","+phone+","+address+","+city+","+gender+","+dob+","+qualification+","+skills+")";
cmd = new SqlCommand(insertstring,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
When I am inserting values into this through asp.net page, its giving following error.
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'sbip'.
Invalid column name 'tttt'.
Invalid column name 'ttt'.
The multi-part identifier "tttttt#sss.ss" could not be bound.
Invalid column name 't'.
Invalid column name 'tttt'.
Invalid column name 'Male'.
Invalid column name 'MCA'.
Invalid column name 'C#'.
where tttt, male mca, etc etc are values that are passed from asp page.
thanks!
use parameters like below and also using statements
string connstring = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
// change this select statement based on your exact column names
string insertstring = "insert into JobRegisteration ([Name] ,[User] ,[Password] ,[Email] ,[Phone],[Address] ,[City] ,[Gender] ,[Dob] ,[Qualification] ,[Skills]) values (#name ,#user ,#password ,#email ,#phone,#address ,#city ,#gender ,#dob ,#qualification ,#skills)";
using (var con = new SqlConnection(connstring))
using(var cmd = new SqlCommand(insertstring, con))
{
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#user", txtUser.Text);
// give all the parameters..
con.Open();
cmd.ExecuteNonQuery();
}
You need to wrap your inserted values with ' otherwise the database treat them as column names:
string insertstring = " insert into JobRegisteration values ('"+name+"','"+user+"','"+password+"','"+email+"','"+phone+"','"+address+"','"+city+"','"+gender+"','"+dob+"','"+qualification+"','"+skills+"')";
Also, as other suggested you really should rely on Prepared Statements to avoid such problems (among others).
There are many solution to your problem.
1) Try to fit with this format:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
2) as said haim770, surround your values with '
3) use sql parameters way
4) or look at Linq, that's really simplify way to work with database
You need to add single quote ' in your query:
string insertstring = " insert into JobRegisteration values ('"+name+"','"+user+"','"+password+"','"+email+"','"+phone+"','"+address+"','"+city+"','"+gender+"','"+dob+"','"+qualification+"','"+skills+"')";
use using (pun!), bind variables (a.k.a. parameters), format your query, when query seems dubious put what you want explicitly...
protected void Button1_Click(object sender, EventArgs e) {
string name = txtName.Text;
string user = txtUser.Text;
string password = txtPwd.Text;
string email = txtEmail.Text;
long phone = Convert.ToInt64(txtPhone.Text); // <- what about +77(555)123-456-78?
string address = txtAddr.Text;
string city = txtCity.Text;
string gender = RadioButtonList1.SelectedItem.ToString();
string dob = txtDOB.Text;
string qualification = DropDownList1.SelectedItem.ToString();
string skills = CheckBoxList1.SelectedItem.ToString();
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString)) {
con.Open();
using(var cmd = con.CreateCommand()) {
cmd.CommandText =
// replace all "field_for_*" for actual fields
#"insert into JobRegisteration(
field_for_name,
field_for_user,
field_for_password,
field_for_email,
field_for_phone,
field_for_address,
field_for_city,
field_for_gender,
field_for_dob,
field_for_qualification,
field_for_skills)
values (
#prm_name,
#prm_user,
#prm_password,
#prm_email,
#prm_phone,
#prm_address,
#prm_city,
#prm_gender,
#prm_dob,
#prm_qualification,
#prm_skills)";
cmd.Parameters.AddWithValue("#prm_name", name);
cmd.Parameters.AddWithValue("#prm_user", user);
cmd.Parameters.AddWithValue("#prm_password", password);
cmd.Parameters.AddWithValue("#prm_email", email);
cmd.Parameters.AddWithValue("#prm_phone", phone);
cmd.Parameters.AddWithValue("#prm_address", address);
cmd.Parameters.AddWithValue("#prm_city", city);
cmd.Parameters.AddWithValue("#prm_gender", gender);
cmd.Parameters.AddWithValue("#prm_dob", dob);
cmd.Parameters.AddWithValue("#prm_qualification", qualification);
cmd.Parameters.AddWithValue("#prm_skills", skills);
cmd.ExecuteNonQuery();
}
}
}
When I try to run this, it gives me the following error message:
Conversion failed when converting the varchar value 'category_id' to data type int.
Here's my SQL and parameter code, I supposed it should work, but it doesn't.
mycmd.CommandText="SELECT * FROM categories WHERE #db_property = #property_id";
// This contains a string "category_id", which is correct.
mycmd.Parameters.Add("#db_property", SqlDbType.VarChar).Value=db_property_field;
// This contains an Int, referring to the category_id in database. As of now, this is 1
mycmd.Parameters.Add("#property_id", SqlDbType.Int).Value=property_id;
After I'm going through this code, I run it through a Reader, and that's where I get the error message above. Been asking teacher, and excellent students in my class, no one can find a clue on, where the problem is.
You shouldn't add field name as parameter. Try to change your script to include actual field id:
mycmd.CommandText = "SELECT * FROM categories WHERE category_id = #property_id";
mycmd.Parameters.Add("#property_id", SqlDbType.Int).Value = property_id;
I'm not sure about your structure, but try the following:
mycmd.CommandText = "SELECT * FROM categories WHERE Cast(#db_property as Int) = #property_id";
Your query is matching the two variables you are passing in so it will either return all the data or none of it! On top of that you are matching a char variable with an int. SQL will try to cast the char variable to an int.
#db_property = #property_id
should your query look like this?
SELECT * FROM categories WHERE db_property = #db_property AND property_id = #property_id
If you look at your statement you are comparing the two parameters. The WHERE clause is not on a table column ("categories") and the two parameters you are passing are different data types. VarChar and Int. When that command is executed the SQL engine is trying to compare two variables of different data types.
If you run the following SQL statements straight against SQL you will receive the same error.
DECLARE #Var1 VARCHAR(100)
DECLARE #Var2 INT
SELECT #Var1 = 'Test', #Var2 = 1
SELECT * FROM dbo.categories WHERE #Var1 = #Var2
You can get solution from the following address:
http://net-informations.com/csprj/data-providers/cs-procedure-parameter.htm
For your information I Just reshape the code and use it to my needs.
Code of Stored Procedure is as follow:
Create PROCEDURE [dbo].[PmSPValidate]
#a varchar(10)
AS
BEGIN
(SELECT AcctDsc,AcctAge
FROM dbo.tblCoa
WHERE AcctNo >= #a)
END
Code of C# :
private void btnThirdTrial_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection;
SqlDataAdapter adapter;
SqlCommand command = new SqlCommand();
SqlParameter param;
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=FIN03;Initial Catalog=CmsTest;Integrated Security=True";
connection = new SqlConnection(connetionString);
connection.Open();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.PmSPValidate";
param = new SqlParameter("#a",Account.Text.ToString ());
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(" Name " + ds.Tables[0].Rows[i][0].ToString() + " Age " + ds.Tables[0].Rows[i][1].ToString());
}
connection.Close();
}