How to write correct grammar of sql query statement in asp.net - sql

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();

Related

How to create web Api execute stored procedure

I work on SQL server 2012 and web API entity framework .NET core 2.2
so I face issue I can't implement web API execute stored Procedure below
Create proc ItemCalculateStock
#ItemId int = NULL,
#InventoryLocation int=NULL
as
begin
SELECT i.itemName,l.InventoryName, SUM(case when QTY > 0 then QTY else 0 end) as PurchasedItem,SUM(case when QTY < 0 then -QTY else 0 end) as ConsumItems,SUM(case when QTY > 0 then QTY else 0 end) + SUM(case when QTY < 0 then QTY else 0 end) as remaining
FROM [dbo].[Invenroty] n with(nolock)
inner join [dbo].[InventoryLocations] l with(nolock) on l.id=n.InventoryLocID
inner join [dbo].[Items] i with(nolock) on n.itemid=i.id
inner join [dbo].[TransactionTypes] t with(nolock) on n.transactionTypeId=t.ID and InventoryLocID=case when #InventoryLocation is null then n.InventoryLocID else #InventoryLocation end
and i.id=case when #ItemId is null then n.itemid else #ItemId end
GROUP BY i.itemName,l.InventoryName
end
so How to get result of stored procedure on web API using Entity Framework .NET core 2.2
[HttpGet("CalculateInventoryData")]
public IActionResult CalculateInventoryData([FromQuery]int optionId, [FromQuery] int ItemId, [FromQuery] int InventoryLocation)
{
// here how to get stored procedure result here
// so i ask question to know how to get result of stored procedure above
}
to call API I use the link below :
https://localhost:44374/api/Inventory/getInventoryData?optionId=1&ItemId=2&InventoryLocation=1
updated Post
I try below
context.Database.ExecuteSqlCommand("ItemCalculateStock #OptionId ,#ItemId,#InventoryLocation ", parameters: new[] {optionId,ItemId,InventoryLocation});
i get error cannot implicitly convert type int into to Microsoft .aspnetcore.mvc.action result
so how to solve issue
The code to execute a stored procedure without parameters is as follows:
SqlConnection conn=new SqlConnection(“connectionString”);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand();
da.SelectCommand.Connection = conn;
da.SelectCommand.CommandText = "NameOfProcedure";
da.SelectCommand.CommandType = CommandType.StoredProcedure;
The code to execute a stored procedure with parameters is as follows (we can declare the function that calls the stored procedure as ExeProcedure(string inputdate)):
param = new SqlParameter("#ParameterName", SqlDbType.DateTime);
param.Direction = ParameterDirection.Input;
param.Value = Convert.ToDateTime(inputdate);
da.SelectCommand.Parameters.Add(param);
This adds an input parameter. If you need to add output parameters:
param = new SqlParameter("#ParameterName", SqlDbType.DateTime);
param.Direction = ParameterDirection.Output;
param.Value = Convert.ToDateTime(inputdate);
da.SelectCommand.Parameters.Add(param);
To get the return value of the stored procedure:
param = new SqlParameter("#ParameterName", SqlDbType.DateTime);
param.Direction = ParameterDirection.ReturnValue;
param.Value = Convert.ToDateTime(inputdate);
da.SelectCommand.Parameters.Add(param);
For more information, please refer to this post:How to run stored procedures in Entity Framework Core?

Problem in updating database with relationship one to many

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+ "'";

Update statement does not update database records

SQL update statement does not update records in database when running the application, but It updates if I run the same Update statement in SQL Server Management studio
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("XXX").ToString())
Dim command As New SqlCommand("Update EmployeeMedicalTest SET [Date tested] = #DateTested, [Next Due date] = #NextDueDate, ECG = #ECG, Lungfunction = #Lungfunction, [Hearing Test] = #HearingTest, [Eye Test] = #EyeTest, [Other Problems] = #OtherProblems, Notes = #Notes WHERE Code = #code", conn)
command.Parameters.AddWithValue("#DateTested", txtDateTested.Text)
command.Parameters.AddWithValue("#NextDueDate", txtNextDueDate.Text)
command.Parameters.AddWithValue("#ECG", txtECG.Text)
command.Parameters.AddWithValue("#Lungfunction", txtLungFunction.Text)
command.Parameters.AddWithValue("#HearingTest", txtHearingTest.Text)
command.Parameters.AddWithValue("#EyeTest", txtEyeTest.Text)
command.Parameters.AddWithValue("#OtherProblems", txtOtherProblems.Text)
command.Parameters.AddWithValue("#Notes", txtNotes.Text)
command.Parameters.AddWithValue("#code", txtClockNo.Text)
conn.Open()
command.ExecuteNonQuery()
lblSaveNotify.Visible = True
conn.Close()

Writing SQL statement to select from multiple rows

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

SUM of all fields in one column

Im trying to calculate the SUM of all the numbers in one column.
The column name is 'Units' the type in integer.
This should work?
cmd3 = New OleDbCommand("SELECT SUM(Units) FROM tblJobs WHERE BookedOut = NULL AND HoldDate = NULL ", con)
lblLiveUnits.Text = cmd3.ExecuteNonQuery()
Thank you
Your query is not correct, you do not want to make something =NULL you should use IS NULL:
SELECT SUM(Units) As TotalUnits
FROM tblJobs
WHERE BookedOut IS NULL
AND HoldDate IS NULL
Then in your code you will use ExecuteScalar:
Int32 lblLiveUnits = 0;
cmd3 = New OleDbCommand("SELECT SUM(Units) As TotalUnits FROM tblJobs WHERE BookedOut IS NULL AND HoldDate IS NULL ", con);
lblLiveUnits = cmd3.ExecuteScalar()