I want to check to see if some of the fields have some unique values - for instance, I want to check if field1, field2 in my table have a value of "YES". If both of them have "Yes" then I want to call some function, but if one of them has "No" value then I want to call some other function. Note in my select statement, I am passing an ID from the query-string. How can I do this?
protected void Check_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e) {
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT ID, Field1, Field2 from MyTabel WHERE ID = '" + Request.QueryString["ID"] + "'", con);
DataTable dt = new DataTable();
da.Fill(dt);
}
If figuring out whether a specific set of criteria exists or not in a given record is all you need, then I can suggest you doing this check on Database side and then using ExecuteScalar to get the result:
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
{
using(SqlCommand cmd = new SqlCommand("SELECT count(*) from MyTabel WHERE ID =#ID And (Field1='Yes' And Field2='Yes')" , con))
{
cmd.parameters.Add("#ID",Request.QueryString["ID"]);
con.open();
int result = cmd.ExecuteScalar();
con.close();
if(result == 1)
// condition exists
// so call success function
else
// call failure function
}
}
Update:
This may not be directly related to the question but to get record Id from detailsView, you need to go through 2 steps:
Set the datakeynames property for the detailsView to the name of your table's primary key name – in this case, ID.
<asp:detailsview datakeynames="ID"
Now you can access the selected Id by
int id = (int)detailsView.SelectedValue;
Check here for more information.
Related
i have simple table item and a text box textbox1 now i want to show max value in textbox i am using the command but code not work
item table: CREATE TABLE TableItem( ItemId NUMBER(10) NOT NULL,
ItemName VARCHAR2(40) NOT NULL, UnitId NUMBER(10) NOT NULL,
CategoryId NUMBER(10) NOT NULL, ItemStatus NUMBER(1) NOT NULL,
SupplierId NUMBER(10)NOT NULL );
and item table insert data:
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(01,'Product-1',21,10,1,51);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(02,'Product-2',22,11,1,52);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(03,'Product-3',23,12,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(04,'Product-4',24,14,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(05,'Product-5',21,12,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(06,'Product-5',23,12,1,52);
now i need max value of itemid
con.Open();
try
{
OleDbCommand cmd4 = new OleDbCommand("SELECT MAX(ItemId) FROM TableItem", con);
textBoxInsert.Text = cmd4.ExecuteScalar().ToString();
}
finally
{
}
con.Close();
You need to create a data adapter, it will fetch your SQL in your database based on your connection. After that you will get a table as result, so you just need to add it to your DataTable and get the rows. There is more interesting implementations, but with this code you can see if it everything is working fine, I've implemented a MySQL version like this:
DataTable _datatable = new DataTable();
MySQLDataAdapter _adapter = new MySQLDataAdapter("SELECT * FROM TEST_TABLE", connection)
_adapter.Fill(_datatable);
myTextBox.Text = _datatable.Rows[0]["ID"].ToString();
On your case, you just need to replace MySQLDataAdapter with OracleDataAdapter, from OracleClient
Reference:
https://msdn.microsoft.com/pt-br/library/system.data.oracleclient.oracledataadapter(v=vs.110).aspx
It is simple. We took the double result for the number we will get in the database.
using (MySqlCommand cmd = new MySqlCommand("SELECT MAX(ItemId) FROM TableItem", con))
{
con.Open();
double result = (Convert.ToDouble(cmd.ExecuteScalar()));
textBoxInsert.Text = result.ToString();
}
I'm getting this error message: Cannot insert the value NULL into column 'id', table ''; column does not allow nulls. INSERT fails. thanks in advance
protected void AddItem(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO Picture (Album, id) VALUES (#Album, #id)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
}
I suppose that ID is an IDENTITY column. Its value is generated automatically by the database engine and you want to know what value has been assigned to your record.
Then you should change your query to
string insertCmd = #"INSERT INTO Picture (Album) VALUES (#Album);
SELECT SCOPE_IDENTITY()";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
int newID = Convert.ToInt32(myCommand.ExecuteScalar());
}
The query text now contains a second instruction SELECT SCOPE_IDENTITY() separated from the first command by a semicolon. SCOPE_IDENTITY returns the last IDENTITY value generated for you by the database engine in the current scope.
Now the command is run using the ExecuteScalar to get back the single value returned by the last statement present in the query text without using any output parameter
I would think that ID is identity. You don't have to add this value. I would try the following code and check the database if you get automatically an ID.
string insertCmd = "INSERT INTO Picture (Album) VALUES (#Album)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.ExecuteNonQuery();
}
I case you want to set the id yourself(withoud automatic increment from the db), you should change the schema of the database removing identity from ID as shown below:
I hope this helps
If you need to stay this column empty you can try to replace to ' '(blank). This will work if you column is not "Key"
Or try to use:
substitute a value when a null value is encountered
NVL( string1, replace_with )
You can do this using stored procedure. Below is the script for Create stored procedure.
CREATE PROCEDURE [dbo].[InsertIntoPicture]
#Album varchar(500)=null,
#id int=0 output
AS
BEGIN
insert INTO Picture(Album)VALUES(#Album)
SET #id=##IDENTITY
END
Below is the code for call stored procedure with C# .
string insertCmd = "InsertIntoPicture";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
Using above code you can insert a date from TextBox and also get last inserted record ID as an output variable as per your requirement.
Thanks .
I have to insert some values in a table while fetching them from another table. Here is my code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
SqlCommand myCommand = new SqlCommand("SELECT Name FROM TableName WHERE Id = '" + Id + "'", con);
SqlDataReader rdr = myCommand.ExecuteReader();
if (dr.HasRows)
{
while (rdr.Read())
{
// User exist - get email
string Name = rdr["Name"].ToString();
}
}
My question is how to insert the name into another table.
I do not want to use a textbox for this the value must be inserted as a variable into other table. I use following script to insert data . but error message is Id not found. Please let me know if I am missing something
SqlCommand cmd = new SqlCommand(#"insert into finalTable (AccountNumber) VALUES (#string)", con);
I use following script to insert data . but error message is Id not found.
SqlCommand cmd = new SqlCommand(#"insert into finalTable (AccountNumber) VALUES
(#string)", con);
You need to specify a value for all columns in the table, unless some columns have default values. Its hard to tell without the exact error message, but it sounds like Id is probably the primary key column and not set to auto increment, so you must supply a value for Id. Since you are inserting, it must be a value not yet used in the table. Depending on your needs, you might want to change finalTable's ID to be auto increment.
On a side note, you are not disposing of things (like your DB connection) that implement IDisposable. The using keyword is your friend here.
The Overview: I've got a dropdown with a list of reports the user can run. In the table that holds this list, I have ReportID, ReportName, SProc and SQLView fields. The idea here is, the user selects a report name, and based on that a specific Stored Procedure will run, and then a specific view will be bound to a datagrid to display the report. For some reports you need to enter a date, for others you don't.
The Code: Here is what I have written;
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
List<ReportData> myReportData = new List<ReportData>();
using (SqlConnection connection1 = new SqlConnection(str2))
{
//Query the Reports table to find the record associated with the selected report
using (SqlCommand cmd = new SqlCommand("SELECT * from tblManagerReports WHERE ReportID = " + cboFilterOption.SelectedValue + "", connection1))
{
connection1.Open();
using (SqlDataReader DT1 = cmd.ExecuteReader())
{
while (DT1.Read())
{
//Read the record into an "array", so you can find the SProc and View names
int MyRptID = Convert.ToInt32(DT1[0]);
string MyRptName = DT1[1].ToString();
string MyRptSproc = DT1[2].ToString();
string MySQLView = DT1[3].ToString();
//Run the Stored Procedure first
SqlConnection connection2 = new SqlConnection(str2);
SqlCommand cmd2 = new SqlCommand("" + MyRptSproc + "", connection2);
//Set up the parameters, if they exist
if (string.IsNullOrEmpty(this.txtStartDate.Text))
{
}
else
{
cmd2.Parameters.Add("#StDate", SqlDbType.Date).Value = txtStartDate.Text;
}
if (string.IsNullOrEmpty(this.txtEndDate.Text))
{
}
else
{
cmd2.Parameters.Add("#EnDate", SqlDbType.Date).Value = txtEndDate.Text;
}
if (MyRptSproc != "")
{
connection2.Open();
cmd2.ExecuteNonQuery();
}
try
{
//Now open the View and bind it to the GridView
string SelectView = "SELECT * FROM " + MySQLView + "";
SqlConnection con = new SqlConnection(str2);
SqlCommand SelectCmd = new SqlCommand(SelectView, con);
SqlDataAdapter SelectAdapter = new SqlDataAdapter(SelectCmd);
//Fill the dataset
DataSet RunReport = new DataSet();
SelectAdapter.Fill(RunReport);
GridView_Reports.DataSource = RunReport;
GridView_Reports.DataBind();
}
catch
{
ScriptManager.RegisterStartupScript(btnSubmit, typeof(Button), "Report Menu", "alert('There is no View associated with this report.\\nPlease contact the developers and let them know of this issue.')", true);
return;
}
}
}
}
}
The Problem: When the code hits the line
cmd2.ExecuteNonQuery();
and there is a start and end date entered, it's telling me "Procedure or function expects parameter '#StDate', which is not supplied." I've stepped through the code and see that cmd2 has 2 parameters, so why isn't the function seeing them?
Additionally, here's the specific stored procedure which is causing the snafu (I've got 2 others that run fine, but neither of them are trying to pass parameters to a stored procedure:
ALTER procedure [dbo].[usp_DailyProc]
#StDate smalldatetime,
#EnDate smalldatetime
AS
BEGIN
IF OBJECT_ID('Temp_DailyProduction') IS NOT NULL
drop table Temp_DailyProduction;
IF OBJECT_ID('Temp_AuditorDailyProduction') IS NOT NULL
drop table Temp_AuditorDailyProduction;
SELECT
[Audit Date],
Auditor,
Count([Doc #]) AS [Claim Count],
Count([Primary Error Code]) AS [Final Error],
SUM(case when [Status]='removed' then 1 else 0 end) as Removed,
SOCNUM
INTO Temp_DailyProc
FROM PreClosed
WHERE (((Get_Next_Status)='Closed' Or (Get_Next_Status)='Panel' Or (Get_Next_Status)='HPanel'))
GROUP BY [Audit Date], Auditor, SOCNUM
HAVING ((([Audit Date]) Between #StDate And #EnDate));
SELECT
TDP.[Audit Date],
TDP.Auditor,
EID.EMPLOYEE AS [Auditor Name],
TDP.[Claim Count],
TDP.[Final Error],
TDP.Removed,
TDP.[Removed]/TDP.[Final Error] AS [Error Removal Ratio],
TDP.SOCNUM
INTO Temp_AuditorDailyProc
FROM Temp_DailyProc TDP
LEFT JOIN PreLookup EID
ON TDP.Auditor = EID.ID_Trim;
drop table Temp_DailyProduction;
END
I think you need to use the AddWithValue method instead of the Add method.
AddWithValue replaces the SqlParameterCollection.Add method that takes
a String and an Object. The overload of Add that takes a string and an
object was deprecated because of possible ambiguity with the
SqlParameterCollection.Add overload that takes a String and a
SqlDbType enumeration value where passing an integer with the string
could be interpreted as being either the parameter value or the
corresponding SqlDbType value. Use AddWithValue whenever you want to
add a parameter by specifying its name and value.
Had another thought, you are passing a string (Text) value as Date parameter. I think you should convert this to a date type. e.g.
cmd2.Parameters.Add("#StDate", SqlDbType.Date).Value = DateTime.Parse(txtStartDate.Text);
A more robust way of doing this would be to use DateTime.TryParseExact.
so I am having an issue with a shopping cart. I am trying to transfer the Title and Price columns out of a cart table (tblCart) and send them into a purchased items table (tblPurchaseItem). This works fine like it is suppose to. Now the problem is that the tblPurchaseItem has an extra column called PurchaseID that is not in the tblCart. Now on a button "Checkout" click this takes place. My issue I am having is that I am trying to set a value to the new rows added into tblPurchaseItem each time the table from cart is transferred over. So say tblCart is added with a list of movies I would like all of them to have the same value in the tblPurchaseItem. The next time somebody clicks the "Checkout" button I would like that new table from tblCart to be sent to tblPurchaseItem to be the value of the last one +1. When I try this my PurchaseID column is staying = to null and is taking no values. Any advice would be greatly appreciated!
Here is my code for the "Checkout" button:
private void Button_Click(object sender, RoutedEventArgs e)
{
purID += 1;
cn.Open();
String cmdString = "INSERT INTO tblPurchaseItem(Title, Price) Select Title, Price from tblCart";
String cmdString3 = "DELETE from tblCart";
String cmdString4 = "Select * from tblPurchaseItem";
SqlCommand cmd = new SqlCommand(cmdString, cn);
SqlCommand cmd3 = new SqlCommand(cmdString3, cn);
SqlCommand cmd4 = new SqlCommand(cmdString4, cn);
da = new SqlDataAdapter(cmd4);
dt = new DataTable("tblPurchaseItem");
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
String cmdString2 = "UPDATE tblPurchaseItem set PurchaseID = '" + purID + "' where PurchaseID is Null";
SqlCommand cmd2 = new SqlCommand(cmdString2, cn);
}
cmd.ExecuteNonQuery();
cmd3.ExecuteNonQuery();
So all in all, say the first table sent to the tblPurchaseItem when the user clicks "Checkout" would be assigned the purID of 1. The next time the Checkout button is clicked I would like those values to be assigned to 2, and so on. So each transaction would have a its own purID.
I've updated the code quite a lot:
cn.Open();
String cmdString = "INSERT INTO tblPurchaseItem(Title, Price, PurchaseID) Select Title, Price, #PurchaseID from tblCart";
SqlCommand cmd = new SqlCommand(cmdString, cn);
cmd.Parameters.AddWithValue("#PurchaseID", purID);
cmd.ExecuteNonQuery();
String cmdString3 = "DELETE from tblCart";
SqlCommand cmd3 = new SqlCommand(cmdString3, cn);
cmd3.ExecuteNonQuery();
My reasoning is that your queries were far too vague, e.g. they affected whole tables indiscriminately. I'm still concerned that you transfer the whole tblCart table and clear it all out. If your system has multiple users, I imagine you would want a UserID column in the cart and only affect rows for that one user.
If I understand you correctly, you need to normalise your database more. For example have a tblPurchase table which represents a single transaction, where tblPurchaseItem contains all the items belonging to the one purchase. Then your tblPurchase table can have an identity int column which provides the purchaseID values for your tblPurchaseItem table. You can do something like the below when inserting:
insert into tblPurchase(customerID, orderDate)
values (#customerID, getdate());
select SCOPE_IDENTITY();
You can run that using ExecuteScalar, then use the int ID returned when inserting rows into tblPurchaseItem.