This might be a silly question to ask. I will appreciate any kind of help.
I'm trying to write a query that count the number of rows based on the logic as below:
count no rows where username = #username and friendsname = #friendsname and username = #friendsname and #friendsname = #username where status = 0
consider the table in the diagram below:
The query should return 1 since id '18' and id '20' have reciprocal values. How will this query be written?
I have written the query as follows which doesn't work:
bool flag = false;
StringBuilder query = new StringBuilder();
query.Append("SELECT Count(id) from friends where username=#username AND friend_username=#friend_username AND username = #friend_username AND friend_username = #username");
query.Append(" AND status=0");
using (SqlConnection con = new SqlConnection(Config.ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query.ToString(), con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#username", username));
cmd.Parameters.Add(new SqlParameter("#friend_username", friendusername));
if (Convert.ToInt32(cmd.ExecuteScalar()) > 0)
flag = true;
}
}
return flag;
If I'm not mistaken you're trying to count rows given a specific #username and #friendusername that have reciprocal values based on your conditions.
Below query should help, though - I have not tested it in action!
SELECT COUNT(*) as reciprocal_values_no
FROM table_name tbl1
WHERE
username = #username
AND friend_username = #friendusername
AND status = 0
AND EXISTS (
SELECT 1 FROM table_name tbl2 WHERE tbl1.username = tbl2.friend_username AND tbl1.friend_username = tbl2.username )
try this
select username,friend_username,status, count(*)
from table_name
group by username,friend_username,status
having count(*) > 1
Related
I'm trying to update my database but I'm getting this error:
System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Data.OleDb.OleDbException: You cannot add or change a record because a related record is required in table 'ItemTypes'.
I'm not sure how to fix it.
I don't know what i need to show so I will just show most of everything.
I've tried to look for a solution and the solutions that I've found said that it's because I'm trying to update the field with a value that is different but I don't understand why because the field is suppose to be the same.
The databases I have the problem with
This is the html part:
<asp:DropDownList ID="ItemType" runat="server">
<asp:ListItem></asp:ListItem>
</asp:DropDownList></td>
This is my code at the PageLoad:
if (!Page.IsPostBack)
{
DataTable dtItem = s.GetItemByIdForUser(Session["ItemCode"].ToString(),Session["Name"].ToString());
ItemCode.Text = dtItem.Rows[0][0].ToString();
ItemName.Text = dtItem.Rows[0][1].ToString();
ItemDes.Text = dtItem.Rows[0][2].ToString();
DataTable Types = s.GetAllItemsTypes();
for (int i = 0; i < Types.Rows.Count; i++)
ItemType.Items.Add(Types.Rows[i][0].ToString());
ItemType.SelectedItem.Text = dtItem.Rows[0][3].ToString();
ItemPrice.Text = dtItem.Rows[0][4].ToString();
Stock.Text = dtItem.Rows[0][5].ToString();
SellerName.Text = dtItem.Rows[0][6].ToString();
Image1.ImageUrl = "~/ProjectPictures/" + dtItem.Rows[0][8].ToString();
}
This is my code that happens when i click at the update:
DataTable dtItem = s.GetItemByIdForUser(Session["ItemCode"].ToString(), Session["Name"].ToString());
i.ItemCode = ItemCode.Text;
i.Name = ItemName.Text;
i.Des = ItemDes.Text;
i.Type = ItemType.SelectedItem.ToString();
i.Price = ItemPrice.Text;
i.Stock = Stock.Text;
i.UserName = SellerName.Text;
if (Pic.HasFile)
{
Pic.SaveAs(Server.MapPath("ProjectPictures/") + Pic.FileName);
i.Pic = Pic.FileName;
}
else
{
i.Pic = dtItem.Rows[0][8].ToString();
}
s.UpdateItem(i, ItemCode.Text);
Session["ItemCode"] = null;
Response.Redirect("Main.aspx");
and this is the sql sentence
string sql = "UPDATE [Items] SET [ItemName]= '#p1' , [ItemDes] = '#p2' , [ItemType] = '#p3' , [Price] = '#p4' , [Stock] = '#p5', [ItemPic] = '#p6' where [ItemCode] = '" +itemCode+ "'";
OleDbCommand cmd = new OleDbCommand(sql);
cmd.Parameters.Add(new OleDbParameter("#p1", OleDbType.VarChar));
cmd.Parameters["#p1"].Value = i.Name;
cmd.Parameters.Add(new OleDbParameter("#p2", OleDbType.VarChar));
cmd.Parameters["#p2"].Value = i.Des;
cmd.Parameters.Add(new OleDbParameter("#p3", OleDbType.VarChar));
cmd.Parameters["#p3"].Value = i.Type;
cmd.Parameters.Add(new OleDbParameter("#p4", OleDbType.VarChar));
cmd.Parameters["#p4"].Value = i.Price;
cmd.Parameters.Add(new OleDbParameter("#p5", OleDbType.VarChar));
cmd.Parameters["#p5"].Value = i.Stock;
cmd.Parameters.Add(new OleDbParameter("#p6", OleDbType.VarChar));
cmd.Parameters["#p6"].Value = i.Pic;
The problem is in your update statement. You have single quotation marks surrounding the parameter names. This means that they are interpreted as literal strings and not as the names of the parameter. So your statement is telling the database to update the ItemType with the value '#p3', (which is not a value in your ItemTypes table hence the foreign key violation) and not with the value in the parameter. In fact your parameters are being totally ignored.
Please also remember when using OleDB that the parameter names are ignored. All that matters is that you provide the parameters in the correct order.
Change your sql to this:
string sql = "UPDATE [Items] SET [ItemName]= #p1 , [ItemDes] = #p2 , [ItemType] = #p3 , [Price] = #p4 , [Stock] = #p5, [ItemPic] = #p6 where [ItemCode] = '" +itemCode+ "'";
I am running a query using OleDbCommand in a database in Excel, containing the following columns:
name, city, inhabitants
My code:
Cmd = new OleDbCommand();
Cmd.Connection = Conn;
Cmd.Parameters.AddWithValue("#city", city);
Cmd.CommandText = "Select City, count(habitants) as h from [Sheet1$] where city = #city group by city";
var Reader = await Cmd.ExecuteReaderAsync();
I get this error:
OleDbException: You tried to execute a query that does not include the specified expression 'city' as part of an aggregate function.
Why does this error appear if it contains the city column?
You can probably work around this error by adding GROUP BY to your query:
Cmd.CommandText = "Select City, count(habitants) as h from [Sheet1$] where city=#city group by City";
Use the FIRST() function for the city:
Cmd.CommandText = "SELECT FIRST(city) AS city, COUNT(habitants) AS h FROM [Sheet1$] WHERE city=#city GROUP BY city";
I want to use join in Oracle 8i. I have my query as below.
I have this query of getting data from two tables using an join, but I get the error SQL command not properly ended.
private List<StamfordProdRelease> GetStamfordProdReleases()
{
List<StamfordProdRelease> list = null;
string srtQry = "SELECT NVL(NULL, 0) ID," +
" DLOG.RELEASEID AS RELEASE_BUILD," +
" TRUNC (DLOGDET.DEPLOYDATE) AS PROD_DEPLOY_DATE," +
" DLOGDET.DEPLOYREQUEST AS BAAR_RFD," +
" DLOG.FILENAMEEXT_VC AS SCRIPT_NAME," +
" DLOG.VERSION," +
" DLOG.REQUEST," +
" DLOG.NOTE AS COMMENTS" +
" FROM ADM_DEPLOYMENTLOGDETAIL DLOGDET" +
" JOIN ADM_DEPLOYMENTLOG DLOG ON DLOG.LOGNO = DLOGDET.LOGNO;";
using (OracleConnection conn = new OracleConnection(Globals.Constants.AppConnectionStringReadOnly))
{
using (OracleCommand objCommand = new OracleCommand(srtQry, conn))
{
objCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
OracleDataAdapter adp = new OracleDataAdapter(objCommand);
conn.Open();
adp.Fill(dt);
if (dt != null)
{
list = ConvertToStamfordProdRelease(dt).ToList();
}
}
}
return list;
}
My target is to insert records into a table.
Keep everything in one set of " and also you only need a single ; to end the SQL query outside of the double quotes.
private List<StamfordProdRelease> GetStamfordProdReleases()
{
List<StamfordProdRelease> list = null;
string srtQry = "SELECT NVL(NULL, 0) ID,
DLOG.RELEASEID AS RELEASE_BUILD,
TRUNC (DLOGDET.DEPLOYDATE) AS PROD_DEPLOY_DATE,
DLOGDET.DEPLOYREQUEST AS BAAR_RFD,
DLOG.FILENAMEEXT_VC AS SCRIPT_NAME,
DLOG.VERSION,
DLOG.REQUEST,
DLOG.NOTE AS COMMENTS
FROM ADM_DEPLOYMENTLOGDETAIL DLOGDET
JOIN ADM_DEPLOYMENTLOG DLOG ON DLOG.LOGNO = DLOGDET.LOGNO";
using (OracleConnection conn = new OracleConnection(Globals.Constants.AppConnectionStringReadOnly))
{
using (OracleCommand objCommand = new OracleCommand(srtQry, conn))
{
objCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
OracleDataAdapter adp = new OracleDataAdapter(objCommand);
conn.Open();
adp.Fill(dt);
if (dt != null)
{
list = ConvertToStamfordProdRelease(dt).ToList();
}
}
}
return list;
}
Oracle 8i did not support standard ANSI SQL JOIN syntax.
That feature was introduced in Oracle 9i Release 2 (aka Oracle 9.2)
Quote from the chapter "What's New in SQL Reference"
SELECT [...] has new ANSI-compliant join syntax.
Don't combine the, strings put all in one.
now I'm facing a problem: I want to get a total number from result='yes' and 'no' from database.
Actually I try a sql query in my sql server studio is working correctly, but when I place the same sql query in the
code of asps.cs, nothing happens, I don't know why. Hope someone can help me to find the problem.
The code as below:
String query_risk1 = "SELECT (SELECT count(result) FROM [rampDB].[dbo].[Answers] WHERE [result]='yes' AND [company] = #deName1 AND [questionID] BETWEEN '1.1a' AND '1.1e' )+(SELECT count(result) FROM [rampDB].[dbo].[Answers] WHERE [result]='no' AND [company] = #deName1 AND [questionID] BETWEEN '1.1a' AND '1.1e')";
DataSet ds_risk = new DataSet();
SqlDataAdapter riskadapter1 = new SqlDataAdapter(query_risk1, sqlConn);
riskadapter1.SelectCommand.Parameters.Add(new SqlParameter("#deName1", site_name));
DataTable risk_table1 = new DataTable();
riskadapter1.Fill(risk_table1);
ds_risk.Tables.Add(risk_table1);
risk_table1 = ds_risk.Tables[0];
grid2.DataSource = ds_risk;
grid2.DataBind();
Try this query
SELECT SUM(CASE WHEN [result] = 'yes' OR [result] = 'no' THEN 1 ELSE 0 END) As Result
FROM [rampDB].[dbo].[answers]
WHERE [company] = #deName1 AND [questionid] BETWEEN '1.1a' AND '1.1e'
May be something like this
String query_risk1 = "SELECT SUM(CASE WHEN [result] = 'yes' OR [result] = 'no' THEN 1 ELSE END) As Result FROM [rampDB].[dbo].[answers] WHERE [company] = #deName1 AND [questionid] BETWEEN '1.1a' AND '1.1e'";
DataSet ds_risk = new DataSet();
SqlDataAdapter riskadapter1 = new SqlDataAdapter(query_risk1, sqlConn);
riskadapter1.SelectCommand.Parameters.Add(new SqlParameter("#deName1", site_name));
DataTable risk_table1 = new DataTable();
riskadapter1.Fill(risk_table1);
ds_risk.Tables.Add(risk_table1);
risk_table1 = ds_risk.Tables[0];
grid2.DataSource = ds_risk;
grid2.DataBind();
your query is similar to this query:
SELECT count(result)
FROM [rampDB].[dbo].[Answers]
WHERE ([result]='yes' OR [result]='no') AND
[company] = #deName1 AND
[questionID] BETWEEN '1.1a' AND '1.1e'
and finally if you use this query you can tru ExecuteScaler() method to get return value of query:
SqlConnection sqlCon = new SqlConnection("YOUR SQL CONNECTIONSTRING");
SqlCommand sqlCom = new SqlCommand("THE QUERY", sqlCon);
sqlCom.Parameters.AddWithValue("#deName1", "SOME VALUE");
sqlCon.Open();
int count = (int)sqlCom.ExecuteScaler();
sqlCon.Close();
Hi all how can I write code below more simply? ... so two sql(OleDb) command in one query.
con.open();
cmd.CommandText = "DELETE * FROM Customers WHERE ID_C = 1";
cmd.ExecuteNonQuery();
cmd.Clone();
cmd.CommandText = "DELETE * FROM Books WHERE ID_B = 1";
cmd.ExecuteNonQuery();
cmd.Clone();
con.close();
Provided that you don't need the number of rows affected (returned by ExecuteNonQuery) you can simply put both commands in the same SQL separated by ";"
con.open();
cmd.CommandText = "DELETE * FROM Customers WHERE ID_C = 1; DELETE * FROM Books WHERE ID_B = 1";
cmd.ExecuteNonQuery();
con.close();