Stored procedures
CREATE PROCEDURE Contributor_Search
#fullname VARCHAR(60)
AS
SELECT
C.id, years_of_experience, portfolio_link, specialization,
notified_id, email, first_name, middle_name, last_name,
birth_date, age
FROM
Contributor C
INNER JOIN
[User] U ON C.id = U.id
WHERE
U.first_name + ' ' + U.middle_name + ' ' + U.last_name = #fullname
CREATE PROCEDURE Show_Original_Content
#contributor_id INT
AS
IF #contributor_id IS NULL
SELECT *
FROM Original_Content OC
INNER JOIN Content C ON OC.id = C.id
INNER JOIN Contributor CO ON C.contributor_id = CO.id
WHERE OC.filter_status = 1
ELSE
SELECT *
FROM Original_Content OC
INNER JOIN Content C ON OC.id = C.id
INNER JOIN Contributor CO ON C.contributor_id = CO.id
WHERE OC.filter_status = 1 AND CO.id = #contributor_id
I want to run the first stored procedure if input is provided, and if not just jump into the second with null; if input is provided and it's ran however, I would like to get an ID using the first procedure and then use it in the second procedure, this is my current approach which unfortunately does not work.
protected void btnSearch_Click(object sender, EventArgs e)
{
string connectionStr = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=iEgypt;";
if(inputName.Value.Trim() != "")
{
using (SqlConnection con = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Contributor_Search";
cmd.CommandType = CommandType.StoredProcedure;
if (inputName.Value.Trim() != "")
{
SqlParameter param = new SqlParameter("#fullname", inputName.Value);
cmd.Parameters.Add(param);
}
else
{
SqlParameter param = new SqlParameter("#fullname", DBNull.Value);
cmd.Parameters.Add(param);
}
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
id = rdr[0].ToString();
con.Close();
}
}
using (SqlConnection con = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Show_Original_Content";
cmd.CommandType = CommandType.StoredProcedure;
if (id != "")
{
SqlParameter param = new SqlParameter("#contributor_id", inputName.Value);
cmd.Parameters.Add(param);
}
else
{
SqlParameter param = new SqlParameter("#contributor_id", DBNull.Value);
cmd.Parameters.Add(param);
}
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
gvSearchResults.DataSource = rdr;
gvSearchResults.DataBind();
}
}
Any help is much appreciated.
In the comments, #vjgn suggests calling the Read method before accessing the rows in the SqlDataReader. For example:
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
id = rdr[0].ToString();
}
That should work... Or alternatively you could use the ExecuteScalar method and not have to worry about opening the reader:
id = cmd.ExecuteScalar()?.ToString() ?? "";
The problem with that is now you are having to check for null, then converting it into an empty string. It is probably better to avoid converting to empty string and just check for both in your if statement.
id = cmd.ExecuteScalar()?.ToString();
...
if (!String.IsNullOrEmpty(id))
Another potential point of error is if the record has a null value in first_name, middle_name, or last_name then your search won't find any results because when you concatenate a null value with a non-null value, you get null. Try changing the where clause to the following:
isnull(U.first_name,'') + ' ' + isnull(U.middle_name,'') + ' ' + isnull(U.last_name,'') = #fullname
This looks like it does an exact search...
Related
When i use the CustomButton for to save the "Full_Name" in the Database [Rooms] => Person then there is just nothing happen. Also if i use the try & catch function, there will be no Exception.
The field in the Database stays Empty.
When i show the required variable in the MessageBox (idPlus2, Full_Name) then it throws me back the right informations.
So i think the problem must be in the UPDATE Sql string but i don't know whats wrong.
private string connstr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\....mdb";
//Path anonymous
string Full_Name;
[Obsolete]
private void customButton1_Click(object sender, EventArgs e)
{
conn = new OleDbConnection(connstr);
conn.Open();
strSQL = "SELECT * FROM [Guests] WHERE ID = ?";
cmd = new OleDbCommand(strSQL, conn);
da = new OleDbDataAdapter(cmd);
int id = CustomComboBox1.SelectedIndex;
int idPlus = id + 1;
cmd.Parameters.Add("?", idPlus);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Full_Name = reader["Vorname"].ToString() + ' ' + reader["Nachname"].ToString();
}
reader.Close();
string insertQuery = #"UPDATE [Rooms] SET Person = #Full_Name WHERE ID = ?";
cmd = new OleDbCommand(insertQuery, conn);
int id2 = customComboBox2.SelectedIndex;
int idPlus2 = id2 + 2;
cmd.Parameters.Add("?", idPlus2);
cmd.Parameters.Add(new OleDbParameter("#Full_Name", Full_Name));
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
LoadTheme();
}
I have the answer
cmd.Parameters.Add("?", OleDbType.VarChar, 255).Value = CustomComboBox1.Texts;
cmd.Parameters.Add("?", idPlus2);
With OleDb you have to use ? for each variable or object which should be added to the database. That means that you can't specify the variable by name in the SQL string. You have to use the same order as the SQL string in C # code to insert the parameters.
I have two tables one table's name is (memberform) and it has columns id,name,mobile example 1,dimitris,69xxxxxxx, and a second table (groups) with columns name,groupname,memberid example dimitris,dancegroup,1 (memberid is the same with id)
I want to extract into a richtextbox where groupname from groups = combobox1 and where memberid from row which groupname exists is same with memberform.id
i'm trying something like this
using (var command = new SqlCommand("select mobile from memberform where memberform.id=groups.memberid and groups.groupname='" + comboBox1.Text + "'", con)) //
using (var reader = command.ExecuteReader())
The raw SQL query is
SELECT M.mobile
FROM memberform M
JOIN groups G ON G.memberid = M.id
WHERE G.groupname = 'dancegroup'
the same can be written in your sqlcommand is
using (var command = new SqlCommand("SELECT M.mobile FROM memberform M JOIN groups G ON G.memberid = M.id WHERE G.groupname = '" + comboBox1.Text + "'", con))
UPDATE:
The above approach can be possible for SQL injection attack, so explicitly pass the parameter by SqlParameter
using (var command = new SqlCommand("SELECT M.mobile FROM memberform M JOIN groups G ON G.memberid = M.id WHERE G.groupname = #GroupName", con))
{
command.Parameters.Add(new SqlParameter("GroupName", comboBox1.Text);
using (var reader = command.ExecuteReader())
....
Why not select from the first table, get the number then use it to select from the second table?
#Edit:
private void GetData()
{
// Get the ID using the name
string id, yourData;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM Table1 WHERE name=#name", con);
cmd.Parameters.Add("#name", "dimitris");
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
id = reader["Id"].ToString();
con.Close();
// Get whatever you want using that ID
cmd.CommandText = "SELECT * FROM Table2 WHERE Id=#id";
cmd.Parameters.Add("#id", id);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
yourData = reader["ColumnName"].ToString();
con.Close();
}
I am trying to call an Oracle stored procedure from a C# program. I am using a SYS_REFCURSOR an the output of the stored procedure. I am getting invalid SQL error when I reach the line
OracleDataReader reader = cmd.ExecuteReader()
in my C# program. I can't figure out why I am getting this invalid SQL error.
Here is the C# code:
private void button1_Click(object sender, EventArgs e)
{
string custname;
int custnbr;
List<Customer> customers = new List<Customer>();
string oradb = "User Id=XXXXX;Password=XXXXX;Data Source=IP:PORT/xxxx;Pooling=false;";
OracleConnection conn = new OracleConnection(oradb);
try
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "PROCEDURE_TEST";
OracleParameter oraP = new OracleParameter();
oraP.ParameterName = "R_RECORDSET";
oraP.OracleDbType = OracleDbType.RefCursor;
oraP.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(oraP);
cmd.CommandType = CommandType.Text;
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
custnbr = reader.GetInt32(0);
custname = reader.GetString(1);
Customer custTemp = new Customer(custnbr, custname);
customers.Add(custTemp);
}
foreach (var cust in customers)
{
textBox1.AppendText("Customer Number: " + cust.custnbr + "\t");
textBox1.AppendText("Customer Name: " + cust.custname + "\r\n");
}
}
catch(Exception ex)
{
textBox1.AppendText(ex.ToString());
conn.Close();
}
}
Here is the Oracle stored procedure:
create or replace PROCEDURE PROCEDURE_TEST
( R_RECORDSET OUT SYS_REFCURSOR) AS
BEGIN
OPEN R_RECORDSET FOR
SELECT POTCHARGECATEGORY, POTCHARGECODE, POTCHARGEDESCRIPTION,
POTCHARGEBASEAMT, SUM(POTCHARGEQTY), SUM(POTCHARGEAMOUNT)
FROM riowner.ccum_customer customer
WHERE ic.collection_Datetime =
TO_DATE('30-SEP-2015 23:59:59','DD-MON-YYYY HH24:MI:SS')
GROUP BY POTCHARGECATEGORY, POTCHARGECODE, POTCHARGEDESCRIPTION,
POTCHARGEBASEAMT;
END PROCEDURE_TEST;
cmd.CommandType = CommandType.Text;
should be
cmd.CommandType = CommandType.StoredProcedure;
As an alternative to MethodMan's answer, you should be able to keep the command type as Text, but change your SQL command to this:
cmd.CommandText = "BEGIN PROCEDURE_TEST END;";
MethodMan's method is better if you just need to call one procedure, but the way I did it above would allow you to do more procedures, so it's something to be aware of in the future.
I can use this loop to give me list of names:
string commandText = #"SELECT ....;";
string connectionString = ConfigurationSettings.AppSettings["connectionString"];
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
try
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
DataTable dt = new DataTable();
dt.Load(reader);
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
SqlCommand addresscommand = new SqlCommand(address, connection);
addresscommand.Parameters.AddWithValue("#companyName", dt.Rows[i][0].ToString());
SqlDataReader addressreader = command.ExecuteReader();
string address = addressreader.GetString(0);
}
}
}
catch (Exception ex)
{
}
}
so the dt.Rows[i][0].ToString() is the name I need to add to all my different sql commands. So inside that for loop I will get each value from executing each sql command, one by one:
SqlCommand addresscommand = new SqlCommand(address, connection);
addresscommand.Parameters.AddWithValue("#companyName", dt.Rows[i][0].ToString());
SqlDataReader addressreader = addresscommand.ExecuteReader();
string comaddress = addressreader.GetString(0);
SqlCommand keyProcessescommand = new SqlCommand(keyProcesses, connection);
keyProcessescommand.Parameters.AddWithValue("#companyName", dt.Rows[i][0].ToString());
SqlDataReader keyProcessesreader = keyProcessescommand.ExecuteReader();
string comkeyProcesses = keyProcessesreader.GetString(0);
SqlCommand standardscommand = new SqlCommand(standards, connection);
standardscommand.Parameters.AddWithValue("#companyName", dt.Rows[i][0].ToString());
SqlDataReader standardsreader = standardscommand.ExecuteReader();
string comstandards = standardsreader.GetString(0);
Where the command string determined by:
string address = #"SELECT address FROM Companies where companyName = #companyName";
string keyProcesses = #" SELECT distinct STUFF((SELECT ', '+ cn.name from WMCCMCategories cn
INNER JOIN CategorySets uc ON uc.categoryId = cn.categoryID
INNER JOIN KeyProcesses u ON u.categorySetId = uc.setId
INNER JOIN Companies c ON c.companyId = u.companyId
WHERE c.companyName = #companyName
ORDER BY cn.name
FOR XML PATH('')), 1, 1, '') AS listStr
FROM WMCCMCategories cnn Group by cnn.name";
string standards = #" SELECT cn.name from WMCCMCategories cn
INNER JOIN CategorySets uc ON uc.categoryId = cn.categoryID
INNER JOIN Companies c ON c.standards = uc.setId
WHERE c.companyName = #companyName";
Can I execute multiple sql commands like above? How is the best way to do that ?
One way you can solve this through JOIN in SQL. However, it may not be right thing to do if it is not representing same columns.
Now in terms of using multiple select in one command. Yes, you can use SqlDataReader with NextResult()
Please see this link:
http://csharp.net-informations.com/data-providers/csharp-multiple-resultsets.htm
i am new to programming. Learning C# and using
visual studio
i made a file with two text boxes. the content of these text boxes
are transferred to another file using javascript
listfile
<script type="text/javascript">
function RunAjax1(custId) {
var custId = document.getElementById("customerId").value;
//var custName = document.getElementById("customerName").value;
jQuery.ajax(
{
url: "CustActions.aspx?id=" + custId +"&custName="+customerName,
type: "GET"
}
).done(function (responseText) {
jQuery("#display").html(responseText)
});
}
</script>
i want to use an if statement before an sql command in order to use one
or the two variables (whichever is not null).
The customerid is integer, while the customerName is a string.
The code is as follows:
actionfile
<% SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ToString());
string cmdText = #"SELECT * FROM Customers where id= #_id";
SqlCommand cmd = new SqlCommand(cmdText, con);
cmd.Parameters.Add("_id", SqlDbType.Int).Value = Convert.ToInt16(Request["id"].ToString());
cmd.Parameters.Add("custName_",SqlDbType.VarChar).Value=Convert.ToChar(Request["custName"].ToString());
DataTable dt = new DataTable();
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
foreach (DataRow dr in dt.Rows)
{
Response.Write(string.Format(#"<tr>
<td>{0}</td>
<td>{1}</td>
That is i want a statement like the one that follows
if (_id is Notnull)
{
string cmdText = #"SELECT * FROM Customers where id= #_id";
}
else
{
string cmdText = #"SELECT * FROM Customers where customerName= #custName_";
}
plus variable declaration to the actionfile
Thanks
<% SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ToString());
string cmdText = _id != null
? #"SELECT * FROM Customers where id= #_id"
: #"SELECT * FROM Customers where customerName= #custName_";
SqlCommand cmd = new SqlCommand(cmdText, con);
cmd.Parameters.Add("_id", SqlDbType.Int).Value = Convert.ToInt16(Request["id"].ToString());
cmd.Parameters.Add("custName_",SqlDbType.VarChar).Value=Convert.ToChar(Request["custName"].ToString());
DataTable dt = new DataTable();
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
Is this what you want? However its not recommended to put so much code into your aspx files.
its better to put make your code accept 2 parameters and then have the stored procedure handle the nulls and it have the if statement
like this
Create proc dosomething
(
-- initialized the values to null if no value is passed in
#id tinyint = NULL
#CustomerName varchar 100 = NULL
)
BEGIN
if #tinyint is NULL and CustomerName is not null
SELECT * FROM Customers where id= #id ";
END
BEGIN
if #CustomerName is NULL and #tinyint is NOT NULL
SELECT * FROM Customers where customerName= #Customername";
END
BEGIN
if #CustomerName is NULL NOT and #tinyint is NOT NULL
SELECT * FROM Customers where (customerName= #Customername and id = #id) ";
END