I have created a stored procedure that takes several parameters and ultimately does an INSERT on two tables. The sp returns with an integer indicating which is positive if one or more rows were added.
If I execute the SP by hand using the SQL Server Management Studio Express I get the proper results, the records are added to both tables and the return values are proper. One is an output parameter indicating the Identity value of the main record, the return value simply >0 if OK.
However, when I use C#, build my connection, command and its associated parameters making sure they match the SP then I get a malfunction.
The problem is that when I call ExecuteNonQuery the integer value it returns is -1 even though calling it from Mgmt. Studio gives a >0 result. Even though it returns -1 I can confirm that the records were added to BOTH tables and that the output parameter (The identity) given to me is also correct. However the return value is always -1.
I have no idea what is going wrong, Since I have SQL Express 2005 I do cannot do profiling :(. I really don't see why this goes wrong and I think using ExecuteScalar is not the best choice for this type of action.
Dear; I got a problem executenonquery in asp.net 2.0. Below as my Code: 1 Dim conn As New SqlConnection(tmpconn)2 Dim cmd1 As New SqlCommand("SP_RPTFABTRANSFER_DYEING_PREV", conn)3 4 cmd1.CommandType = CommandType.StoredProcedure5 cmd1.CommandTimeout = 9006 cmd1.Parameters.Add(New SqlParameter("@aSTDATE", SqlDbType.VarChar, 10))7 cmd1.Parameters.Add(New SqlParameter("@aEDDATE", SqlDbType.VarChar, 10))8 cmd1.Parameters.Add(New SqlParameter("@aBUYERID", SqlDbType.VarChar, 10)) 9 cmd1.Parameters.Add(New SqlParameter("@aFACTORYID", SqlDbType.VarChar, 10))10 cmd1.Parameters.Add(New SqlParameter("@aFabGrpId", SqlDbType.VarChar, 10))11 cmd1.Parameters.Add(New SqlParameter("@aFABSUPPIDFROM", SqlDbType.VarChar, 10))12 cmd1.Parameters.Add(New SqlParameter("@aFABSUPPIDTO", SqlDbType.VarChar, 10))13 cmd1.Parameters.Add(New SqlParameter("@aUSERID", SqlDbType.VarChar, 20))14 cmd1.Parameters.Add(New SqlParameter("@aDelType", SqlDbType.VarChar, 20))15 16 cmd1.Parameters("@aSTDATE").Value = lstartdt17 cmd1.Parameters("@aEDDATE").Value = lenddt18 cmd1.Parameters("@aBUYERID").Value = Trim(dropBuyer.SelectedValue)19 cmd1.Parameters("@aFACTORYID").Value = Trim(dropFactory.SelectedValue)20 cmd1.Parameters("@aFabGrpId").Value = lFabGrp21 cmd1.Parameters("@aFABSUPPIDFROM").Value = fabFrom22 cmd1.Parameters("@aFABSUPPIDTO").Value = fabTo23 cmd1.Parameters("@aUSERID").Value = Session("UID").ToString24 cmd1.Parameters("@aDelType").Value = lDelType25 Try26 conn.Open()27 cmd1.ExecuteNonQuery()28 conn.Close()29 Catch ex As Exception30 lblerr.Visible = True31 lblerr.Text = ex.Message32 Finally33 conn.Close()34 End Try Web.Config<add name="oldtextileConnectionString" connectionString="Data Source=xx.xx.xx.xx;Initial Catalog=ERP;Integrated Security=TRUE;Connection Lifetime=0;Min Pool Size =0;Max Pool Size=1000;Pooling=true;" providerName="System.Data.SqlClient"/> This Code running on asp only 2min Execute time. But i try it on Asp.net 2.0 take a long time about 15min or request time out error. Could any one can give me some tips or hits? Help much appreciated. Thanks
I hope you would help me in this problem. I use the code below for executenonquery command for mdb DB.But I do not know the changes I should made when Using SQL2005.-------------Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; " & _ "Data Source=C:ASPNET20dataNorthwind.mdb" Dim dbConnection As New OleDbConnection(connectionString) dbConnection.Open() Dim commandString As String = "INSERT INTO Employees(FirstName, LastName) " & _ "Values(@FirstName, @LastName)" Dim dbCommand As New OleDbCommand(commandString, dbConnection) Dim firstNameParam As New OleDbParameter("@FirstName", OleDbType.VarChar, 10) firstNameParam.Value = txtFirstName.Text dbCommand.Parameters.Add(firstNameParam) Dim lastNameParam As New OleDbParameter("@LastName", OleDbType.VarChar, 20) LastNameParam.Value = txtLastName.Text dbCommand.Parameters.Add(LastNameParam) dbCommand.ExecuteNonQuery() dbConnection.Close()--------
Hi, I am trying to execute a nonquery as follows (look for bold):Dim connStringSQL As New SqlConnection("Data Source=...***...Trusted_Connection=False")'// Create the new OLEDB connection to Indexing ServiceDim connInd As New System.Data.OleDb.OleDbConnection(connStringInd)Dim commandInd As New System.Data.OleDb.OleDbDataAdapter(strQueryCombined, connInd)Dim commandSQL As New SqlCommand("GetAssetList2", connStringSQL)commandSQL.CommandType = Data.CommandType.StoredProcedureDim resultDS As New Data.DataSet()Dim resultDA As New SqlDataAdapter()'// Fill the dataset with valuescommandInd.Fill(resultDS)'// Get the XML values of the dataset to send to SQL server and run a new query...'// Return the number of resultsresultCount.Text = source.Count.ToStringresults.DataSource = sourceresults.DataBind()'// Record the searchcommandSQL = New SqlCommand("RecordSearch", connStringSQL)commandSQL.Parameters.Clear()commandSQL.Parameters.Add("@userName", Data.SqlDbType.VarChar, 50).Value = authUser.Text()commandSQL.Parameters.Add("@createdDateTime", Data.SqlDbType.DateTime).Value = DateTime.Now()commandSQL.Parameters.Add("@numRows", Data.SqlDbType.Int, 1000).Value = resultCount.TextcommandSQL.Parameters.Add("@searchString", Data.SqlDbType.VarChar, 1000).Value = searchText.TextconnStringSQL.Open()commandSQL.ExecuteNonQuery()connStringSQL.Close() The stored procedure looks like this:Use GTGAssetsDROP PROC dbo.RecordSearch;--New ProcedureGOCREATE PROC dbo.RecordSearch(@userName varchar(50),@createdDateTime DateTime,@numRows varchar(1000),@searchString varchar(1000))ASBEGINSET NOCOUNT ONINSERT INTO SearchLog (SearchString, CreatedByUser, CreatedDTTM, RowsReturned) VALUES (@searchString, @userName, @createdDateTime, @numRows)ENDGOAny ideas as to why this error is appearing? Incorrect syntax near 'RecordSearch'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near 'RecordSearch'.Source Error: Line 169: commandSQL.Parameters.Add("@searchString", Data.SqlDbType.VarChar, 1000).Value = searchText.Text Line 170: connStringSQL.Open() Line 171: commandSQL.ExecuteNonQuery() Line 172: connStringSQL.Close() Line 173: End IfMany thanks!James
When I try to insert a record with the ExecuteNonQuery command, I get the following error information. Any clues why? Thanks. SSqlException was unhandled by user code...Message="Incorrect syntax near [output of one of my field names]."...[Item detail:] In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user. My code: Private objCmd As SqlCommandPrivate strConn As New SqlConnection(ConfigurationManager.AppSettings("conn"))...objCmd = New SqlCommand("INSERT INTO tblUsers (UserID,FName,LName,PrimLang1,Ctry,Phone)" & _"VALUES('" & strUser & "','" & strFName.Text & "','" & strLName.Text & "', '" & strLang.Text & "', '" & strCtry.Text & "', '" & strPhone.Text & "'" _, strConn)strConn.Open()objCmd.ExecuteNonQuery()
Hi,I am developing a small application where in I need to take a few data from the user and put it on the DB. I have stored procs for the same. I am getting an error when I execute the ExecuteNonQuery() command. the error is as follows: System.InvalidCastException: Object must implement IConvertible. at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Intranet_New.leaveForm.btnSubmit_Click(Object sender, EventArgs e) in c:inetpubwwwrootintranet_newleaveform.aspx.cs:line 138 Snippet of code: try { con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["SqlCon"]); cmd = new SqlCommand(); cmd.Connection = con;
( @empid as char(20), @empName as nvarchar(50), @totalLeave as decimal(9) = 12, @LeaveFrom as datetime, @LeaveTo as datetime, @TotalDays as bigint, @TypeOfLeave as nvarchar(50), @ReasonOfLeave as nvarchar(1000), @RemainigLeave as decimal(9) ) /* ( @parameter1 datatype = default value, @parameter2 datatype OUTPUT ) */ AS /* SET NOCOUNT ON */
HI I am using ExecuteNonQuery to run an UPDATE statement but i keep getting the following error message: "ExecuteNonQuery: Connection property has not been initialized. " this is my code can anyone see what is wrong?
DBCommand.CommandType = CommandType.TextDBCommand.CommandText = queryCourse DBConnection.Open() ExecuteNonQuery = DBCommand.ExecuteNonQuery() DBCommand.ExecuteNonQuery() DBConnection.Close() help would be appreciated.
I have a DataAccess that has "cmd.ExecuteNonQuery" and another file SqlTableProfileProvider for a SandBox project(from ASP.NET) for a Custom TableProfileProvider. That also has a cmd.ExecuteNonQuery even thou these are 2 different files i get an error after debug.
Question is are they conflicting ? if so how can i fix this.
Code Snippets for both provided below the 2nd cmd.ExecuteNonQuery that is producing the Error is Commented in Orange...Thxs for the help Rattlerr
Incorrect syntax near ','.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near ','.
Source Error:
Line 454: cmd.CommandType = CommandType.Text; Line 455: Line 456: cmd.ExecuteNonQuery(); Line 457: Line 458: // Need to close reader before we try to update
I have an interesting error that shows up on Windows Mobile 6.0 devices but does not appear to affect Windows Mobile 5.0 devices. The application runs in .NET CF 2.0 on SQL CE 3.0 using Merge Replication. When the application starts, there is an ExecuteNonQuery prior to calling the first synchronization. It appears that once the application has replicated that you can no longer create a connection to the database and run an ExecuteNonQuery successfully. If you have already created the SqlCeConnection and just open and close it as needed that you are able to run ExecuteNonQuery commands.
In Windows Monile 6.0; however, I eventually run out of memory, like there is a leak someplace. Does anyone have any ideas for how you would actually be able to dispose of the SqlCeConnection and recreate it each time? Does calling .Close() release all the native resources on a SqlCeConnection? I am trying out one more modification, I realized the SqlCeReplication object was not being disposed of and I'm guessing this probably also uses native resources; can anyone confirm this would also potentially cause a problem?
The application works but it is aggravating to have to softboot once in awhile to recover the memory, I'd like to move beyond it. Any ideas would be great!
System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'VSReferenceNumber'. at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at ASP.workingdatagrid2_aspx.myDataGrid_Update(Object Sender, DataGridCommandEventArgs e) in C:Inetpubwwwrootuapworkingdatagrid2.aspx:line 64
Here's the code::
<script runat="server">
//public string ConnString = "server=atw_data01;database=UAP;uid=atw_cheryl.theobald;pwd=nudibranch;"; public string ConnString = "Server=(local); user id=sa;password=;initial catalog = UAP;"; void BindData() { //-- Using the Try statement, we attempt to connect to our //-- database, execute a SqlDataAdapter to store our data, //-- populate a dataset and then bind that dataset //-- to our DataGrid. try { SqlConnection SqlConn = new SqlConnection(ConnString); string SqlString = "SELECT [uapID], [DealershipName], [AutoExchangeClientID], [VSReferenceNumber] FROM uapForm"; SqlDataAdapter SqlComm = new SqlDataAdapter(SqlString, SqlConn); DataSet customerData = new DataSet(); SqlComm.Fill(customerData, "uapForm");
//-- If we are not able to connect, display a friendly error catch (Exception e) { ErrorLabel.Text = "Not able to connect to database. See description below: <P>"; ErrorLabel.Text += e.ToString(); }
}
void myDataGrid_Update (object Sender, DataGridCommandEventArgs e) { //-- Take the data from each textbox in our editable item //-- and assign that text to a string variable string uapID = Convert.ToString(e.Item.Cells[0].Text); string DealershipName = ((TextBox) e.Item.Cells[1].Controls[0]).Text; string AutoExchangeClientID = ((TextBox) e.Item.Cells[2].Controls[0]).Text; string VSReferenceNumber = ((TextBox) e.Item.Cells[3].Controls[0]).Text;
//-- Again, using the Try statement, attempt to connect to our database //-- and make an update with the data from our datagrid SqlConnection SqlConn = new SqlConnection(ConnString); try { SqlConn.Open(); string SqlString = "UPDATE uapForm "; SqlString += "SET DealershipName = '" + DealershipName.Replace("'", "''") + "', "; SqlString += "AutoExchangeClientID = '" + AutoExchangeClientID.Replace("'", "''") + "' "; SqlString += "VSReferenceNumber = '" + VSReferenceNumber.Replace("'", "''") + "', "; SqlString += " WHERE uapID = '" + uapID + "'"; SqlCommand SqlComm = new SqlCommand(SqlString, SqlConn); SqlComm.ExecuteNonQuery(); SqlConn.Close(); SqlComm.Dispose(); SqlConn.Dispose(); }
//-- If for some reason we cannot connect, display a friendly error. catch (Exception exc) { ErrorLabel.Text = "Not able to connect to database. <br>Please See description below:<P> <P>"; ErrorLabel.Text += exc.ToString(); }
void myDataGrid_Edit(object Sender, DataGridCommandEventArgs e) { //-- Set the edit focus to the item that was selected myDataGrid.EditItemIndex = (int) e.Item.ItemIndex; //-- Rebind our datagrid BindData(); }
void Page_Load (object Sender, EventArgs e) { //-- If the page is not posting back, bind our datagrid if (!Page.IsPostBack) { BindData(); } }
Hi, I'm using .net 2.0 and I have created a stored procedure (sql server DB) which has one insert statement with 2 input parameters. When I execute this stored procedure using ExecuteNonQuery(), it always returning -1. I want to know how many records are effected. I want to know if there is any error. Help appreciated.
I was trying an RDA Demo project. However, everytime I pull the data from Sql Server 2005 and then move on to add a row to the table using SqlCeCommand.ExecuteNonQuery(), the application fails catastrophically without giving any exception and simply exits!
When I have pulled the data once and this application has shut down (exited) I can open it again and then continue normally but I can't expect the application to PULL the data and then even add or update a row to that table. I can do select queries fine. Why would this happen?
I am disposing all the objects that I use in both the scenarios, or atleast I believe so. Does any one have any idea?
Hy, again! I am at the begining of an application. I have some modules that insert, delete and update only one row at one table. My question is should I use dataadapter.Update() or ExecuteNonQuery(). I prefer ExecuteNonQuery because I want to build a class : DataLayer to implement my own InsertProcedure(), UpdateProcedure(),DeleteProcedure(). I want speed in my application, so which is the best: dataadapter.Update() OR ExecuteNonQuery(). Thank you!
I'm using VB.Net 2008 with SQL Compact 3.5. After trying forever, I finally got my app to open a retrieve a record from a table. Now, when I try to update the record, I get an error on the ExecuteNonQuery statement. The error says I am "attempting to read or write protected memory". The code works perfectly with an Access database.
Hey, I have a page that inserts into a customers table in the DataBase a new customer account using this function: Public Function InsertCustomers(ByRef sessionid, ByVal email, ByVal pass, Optional ByVal fname = "", Optional ByVal lname = "", Optional ByVal company = "", Optional ByVal pobox = "", Optional ByVal add1 = "", Optional ByVal add2 = "", Optional ByVal city = "", Optional ByVal state = "", Optional ByVal postalcode = "", Optional ByVal country = 0, Optional ByVal tel = "") Dim result As New DataSet Dim tempid As Integer Dim conn As New SqlConnection(ConfigurationSettings.AppSettings("Conn")) Dim Adcust As New SqlDataAdapter Adcust.InsertCommand = New SqlCommand Adcust.SelectCommand = New SqlCommand Adcust.InsertCommand.Connection = conn Adcust.SelectCommand.Connection = conn sessionExists(email, sessionid, 1) conn.Open() If fname = "" Then Adcust.InsertCommand.CommandText = "Insert Into neelwafu.customers(email,password,sessionid) Values('" & email & "','" & pass & "','" & sessionid & "')" Else Dim strsql As String strsql = "Insert Into neelwafu.customers" strsql = strsql & "(sessionid,email,password,fname,lname,company,pobox,address,address2,city,state,postalcode,countrycode,tel) values(" strsql = strsql & "'" & sessionid & "','" & email & "','" & pass & "','" & fname & "','" & lname & "','" & company & "','" & pobox & "','" & add1 & "','" & add2 & "','" & city & "','" & state & "','" & postalcode & "', " & country & ",'" & tel & "')" Adcust.InsertCommand.CommandText = strsql End If Adcust.InsertCommand.ExecuteNonQuery() Adcust.SelectCommand.CommandText = "Select Max(id) from neelwafu.Customers" tempid = CInt(Adcust.SelectCommand.ExecuteScalar()) conn.Close() Return tempid End Function -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Now, I am getting an error: Violation of PRIMARY KEY constraint 'PK_customers_1'. Cannot insert duplicate key in object 'customers'. The statement has been terminated. --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The customers table has as a primary key the 'email'..... so plz can I know why am I getting this error ???? Thank you in advance Hiba
Hi , Iam new to vs2005. Iam trying to integrate Authorize.net for transactions in my site. When i tested it worked fine .But when i put it in live for Amex cards it is giving me sqlerror. Here is my code using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using System.Net; using System.IO; public partial class Paymentprocessing : System.Web.UI.Page {SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["strConn"]); string permLevel = "";protected void Page_Load(object sender, EventArgs e) {if (Session["displayname"] == null || Session["franchiseid"] == null || Session["username"] == null) {Response.Redirect("Default.aspx"); } else {lblusrname.Text = Session["displayname"].ToString(); }string strSelectquery = ""; strSelectquery = "select userPermissionLevel,Franchise_ID from tblUsers where User_Name='" + Session["username"].ToString()+"'";SqlCommand objCmd = new SqlCommand(strSelectquery, objConn);SqlDataReader objDr; objConn.Open(); objDr = objCmd.ExecuteReader(); if (objDr.Read()) { permLevel = objDr[0].ToString(); } objDr.Close(); objConn.Close();if (int.Parse(permLevel) == 99) {pnlRefundCC.Visible = true; pnlRefundCA.Visible = true;pnlTransact.Visible = true; pnlPaymentInfo.Visible = true;pnlCardifo.Visible = true; } else {pnlPaymentInfo.Visible = true; pnlCardifo.Visible = true;pnlRefundCC.Visible = false; pnlRefundCA.Visible = false;pnlTransact.Visible = false; } }protected void RadioButton3_CheckedChanged(object sender, EventArgs e) {pnlTransact.Visible = false; pnlPaymentCCA.Visible = false;pnlOrgTransID.Visible = true;pnlCardifo.Visible = true;
Here is the error iam getting server Error in '/' Application. ----------------ExecuteNonQuery: CommandText property has not been initialized Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: ExecuteNonQuery: CommandText property has not been initializedSource Error: Line 431: SqlCommand cmd1 = new SqlCommand(strInsert,objConn);Line 432: objConn.Open();Line 433: cmd1.ExecuteNonQuery();Line 434: objConn.Close();Line 435: Source File: d:Websitesserviceinfo.comsecurePaymentprocessing.aspx.cs Line: 433 Stack Trace: [InvalidOperationException: ExecuteNonQuery: CommandText property hasnot been initialized] System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) +873524 System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +72 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135 Paymentprocessing.btnSubmit_Click(Object sender, EventArgs e) in d:Websitesxyassss.aspx.cs:433 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102 ----------------Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210
I am working on a web service method that will return weather or not a page url is stored in the database but the ExecuteNonQuery keeps returning -1. I was just wondering if i was doing anything wrong or why the ExecuteNonQuery method does not return a value of 1 or more indicating that the pageurl exists in the database? I have tried using the SQLDataReader as well to no effect and I have verified that SELECT statement refers to valid table and field names. Any help or pointers would be appreciated. I'm still kind of a newb when it comes to db programming. 1 <WebMethod()> _2 Public Function IsPageStored(ByVal pageurl As String) As Boolean3 If String.IsNullOrEmpty(pageurl) Then Return False4 5 Dim conn As New SqlConnection()6 conn.ConnectionString = ConfigurationManager.ConnectionStrings("dbStoredList").ConnectionString7 8 Dim cmd As String 9 cmd = "SELECT [" & Constants.SourceFieldName & "] " 10 cmd &= "FROM [" & Constants.StoredCopyTableName & "] " 11 cmd &= "WHERE ([" & Constants.SourceFieldName & "] = '@Source')" 12 Dim C As New SqlCommand(cmd, conn)13 C.Parameters.AddWithValue("@Source", New SqlTypes.SqlString(pageurl))14 C.Parameters.Item("@Source").CompareInfo = SqlTypes.SqlCompareOptions.IgnoreCase15 16 conn.Open()17 18 Dim exists As Boolean = False 19 exists = (C.ExecuteNonQuery > 0)20 21 conn.Close()22 C.Dispose()23 C = Nothing 24 conn.Dispose()25 conn = Nothing26 27 Return exists28 End Function 29
My understanding from a previous thread was that ExecuteNonQuery() could be used to display the number of rows returned. Does this also work when calling stored procedures and passing parameters? I have code (shown) that perfectly calls and returns Distinct models downloaded by Country. Yet the rowCount variable displays a -1. What should I do?Dim myCommand As New SqlClient.SqlCommand myCommand.CommandText = "ap_Select_ModelRequests_RequestDateTime" myCommand.CommandType = CommandType.StoredProcedure myCommand.Parameters.AddWithValue("@selectDate", dateEntered) myCommand.Parameters.AddWithValue("@selectCountry", CInt(selectCountry)) myCommand.Connection = con con.Open() Dim rowCount As Integer = myCommand.ExecuteNonQuery() numberParts.Text = rowCount.ToString con.Close() Thank you.
Hi all! I've been banging my head on this for way to long and decided it's time to reach out for help. I'll try to be complete and concise with this, but this will end up being lengthy most likely. The crux of the issue is that I apparently do not have any control over what is returned from a stored proc via the SqlCommand.ExecuteNonQuery method. I want the procedure to explicitly return 0 if the proc was successful, otherwise it will return the error code generated. A value of -1 is consistently being returned when SET NOCOUNT ON is in place, and when not, a 1 is returned. This seems to be ignoring the fact that I have RETURN 0 at the end of the proc. Perhaps I'm missing something, but if I RETURN 0, I should get 0...here is the procedure:1 ALTER PROCEDURE [dbo].[epsp_EditCities] 2 @CityId int = null, 3 @City varchar(50), 4 @CreatedBy int, 5 @UpdatedBy int, 6 @ActionType varchar(1) = 'X', 7 @Identity int = 0 OUT, 8 @RowCount int = 0 OUT 9 10 AS 11 DECLARE @ERROR int -- Local @@ERROR 12 13 14 SET NOCOUNT ON 15 BEGIN TRAN 16 17 IF @ActionType = 'I' /* --- INSERT --- */ 18 BEGIN 19 20 INSERT INTO [EnrollmentPrograms].[dbo].[Cities] 21 ([City] 22 ,[CreatedBy] 23 ,[UpdatedBy]) 24 VALUES 25 (@City 26 ,@CreatedBy 27 ,@UpdatedBy) 28 SET @Identity = SCOPE_IDENTITY() 29 30 END 31 32 IF @ActionType = 'U' /* --- UPDATE --- */ 33 BEGIN 34 35 UPDATE [EnrollmentPrograms].[dbo].[Cities] 36 SET [City] = @City 37 ,[UpdatedBy] = @UpdatedBy 38 WHERE CityId = @CityId 39 END 40 41 IF @ActionType = 'D' /* --- DELETE --- */ 42 BEGIN 43 44 DELETE FROM [EnrollmentPrograms].[dbo].[Cities] 45 WHERE CityId = @CityId 46 END 47 48 49 -- Error checking (place this after every statement) -- 50 SET @ERROR = @@ERROR 51 SET @RowCount = @@ROWCOUNT 52 53 IF @ERROR != 0 GOTO HANDLE_ERROR 54 55 COMMIT TRAN -- No Errors, so go ahead 56 57 RETURN 0 58 59 HANDLE_ERROR: 60 ROLLBACK TRAN 61 RETURN @ERRORAnd a fascinating tidbit is the results from this which shows the return value as 0:1 DECLARE@return_value int, 2 @Identity int--, 3 --@RowCount int 4 5 EXEC@return_value = [dbo].[epsp_EditCities] 6 @CityId = 1, 7 @City = N'Agoura Hills', 8 @CreatedBy = 1, 9 @UpdatedBy = 1, 10 @ActionType = N'U', 11 @Identity = @Identity OUTPUT--, 12 --@RowCount = @RowCount OUTPUT 13 14 SELECT@Identity as N'@Identity'--, 15 --@RowCount as N'@RowCount' 16 17 SELECTReturnValue = @return_value
And finally, here is the C# call that always returns -1: retVal = cmd.ExecuteNonQuery(); Now, I've tried almost all variations and unit tests on the procedure that I could dream up. Commenting this out and putting this in etc....I still remain unable to fix the return code to 0 and get that result into my retVal var. Any love? Much thanks in advance for spending time on my issue! Cheers! Wayne
I am trying to create a web form that will be used to create new users. The first step that I am taking is creating a web form that can check the username against a database to see if it already exists. I would it to do this on the fly, if possible. When I execute my current code, I get the following error:
ExecuteNonQuery: Connection property has not been initialized
Below is the code from the page itself: ----- <!-- #INCLUDE FILE="../include/context.inc" --> <!-- #INCLUDE FILE="../include/db_access.inc" -->
<script language="VB" runat="server">
Sub CheckButton_Click(Sender as Object, e as EventArgs)
cmd.ExecuteNonQuery() result = cmd.Parameters("result").Value
If result <> 1 Then CheckResults.Text="<font color=""#ff0000"">Username already exists!</font>" Else CheckResults.Text="<font color=""#009900"">Username is available.</font>" End If
Can anyone see why I might get this error? Here are some more details of the error:
Line 15: cmd.Parameters.Add( "@userName", OdbcType.VarChar, 100 ).Value = Request.Form("userName") Line 16: *Line 17: cmd.ExecuteNonQuery() Line 18: result = cmd.Parameters("result").Value
I was racking my brains trying to figure out why SomeCommand.ExecuteNonQuery() was not returning any rows... SQL Server 2005 likes to put the SET NOCOUNT ON statement in every stored procedure you write. By hiding the count of records touched by your query, you also disable the results to be consumed by your application. So I don't recommend using this statement for your stored procedures and ASP.NET applications, as this functionality is fairly critical for error trapping.
I have a VB.net 2005 application that uses both System.Data.SqlClient and System.Data.SqlServerCe which has worked on PC2003 handhelds but falls over in Windows Mobile 5. It seems to be when I have used a SqlClient connection and then use ExecuteNonQuery on the local sdf file - the application just bombs out - no error message, nothing.
Weirdly, if I am connected to a CE database through Query Analyzer 3.0 at the same time as running this application, everything works fine. Do I need to 'initialize' something that Query Analyzer seems to be doing in order to make this work?
I have done a SQL statement INSERT for my coding. The program compiled and run the insertion with no error occurred. But after the compilation I found out that my database is not populated at all.
I tried the data insertion using the manual query, and I work perfectly.
So the problem now is that I do not know why my codes did not insert the data into my database. Will like to get some advise. Thanks
My codes are pasted in http://www.pastebin.ca/320102 The Debug.Writeline in the code is in http://www.pastebin.ca/320108
When I use ExecuteNonQuery() with the stored procedure below it returns -1. However, when i tried to get rid of the if/else statements and just leave one insert statement for testing purposes, ExecuteNonQuery() returns the correct affected rows which is 1. So it seems like ExecuteNonQuery() doesn't work when the INSERT statement is inside the IF..ELSE. Can anybody help me with this problem? I haven't tried using @@RowCount because I really want to use ExecuteNonQuery() to do this because I don't want to rewrite my DAL. Thanks in advance -- With if/else ExecuteNonQuery returns -1ALTER PROCEDURE [dbo].[SP_AddObjectContribution] @ObjectId int, @FanId int, @DateContributed DateTime, @Notes nvarchar(512), @ObjectType intASBEGIN BEGIN TRAN IF @ObjectType = 2 BEGIN INSERT INTO FighterContributions (FighterId, FanId, DateContributed, Notes) VALUES (@ObjectId, @FanId, @DateContributed, @Notes) END ELSE IF @ObjectType = 3 BEGIN INSERT INTO FighterPhotoContributions (FighterPhotoId, FanId, DateContributed, Notes) VALUES (@ObjectId, @FanId, @DateContributed, @Notes) END ELSE IF @ObjectType = 4 BEGIN INSERT INTO OrganizationContributions (OrganizationId, FanId, DateContributed, Notes) VALUES (@ObjectId, @FanId, @DateContributed, @Notes) END ELSE IF @ObjectType = 5 BEGIN INSERT INTO EventContributions (EventId, FanId, DateContributed, Notes) VALUES (@ObjectId, @FanId, @DateContributed, @Notes) END ELSE IF @ObjectType = 6 BEGIN INSERT INTO FightContributions (FightId, FanId, DateContributed, Notes) VALUES (@ObjectId, @FanId, @DateContributed, @Notes) END ELSE IF @ObjectType = 7 BEGIN INSERT INTO FightPhotoContributions (FightPhotoId, FanId, DateContributed, Notes) VALUES (@ObjectId, @FanId, @DateContributed, @Notes) END IF @@ERROR <> 0 BEGIN ROLLBACK RETURN END COMMIT TRANEND -- Without if/else ExecuteNonQuery returns 1ALTER PROCEDURE [dbo].[SP_AddObjectContribution] @ObjectId int, @FanId int, @DateContributed DateTime, @Notes nvarchar(512), @ObjectType int AS
BEGIN
BEGIN TRAN INSERT INTO FighterContributions (FighterId, FanId, DateContributed, Notes) VALUES (@ObjectId, @FanId, @DateContributed, @Notes) IF @@ERROR <> 0 BEGIN ROLLBACK RETURN END
Please let me know what is wrong with my code below. I keep getting the "Incorrect syntax near 'UpdateInfoByAccountAndFullName'." error when I execute cmd.executenonquery. I highlighted the part that errors out. Thanks a lot. --------------------------------------------------------------------------------------------------------------------------- public bool Update( string newaccount, string newfullname, string rep, string zip, string comment, string oldaccount, string oldfullname ) { SqlConnection cn = new SqlConnection(_connectionstring); SqlCommand cmd = new SqlCommand("UpdateInfoByAccountAndFullName", cn); cmd.Parameters.AddWithValue("@newaccount", newaccount); cmd.Parameters.AddWithValue("@newfullname", newfullname); cmd.Parameters.AddWithValue("@rep", rep); cmd.Parameters.AddWithValue("@zip", zip); cmd.Parameters.AddWithValue("@comments", comment); cmd.Parameters.AddWithValue("@oldaccount", oldaccount); cmd.Parameters.AddWithValue("@oldfullname", oldfullname); using (cn) { cn.Open(); return cmd.ExecuteNonQuery() > 1; } }
Here is the table that I am wanting to insert the information into (BTW I am wanting the UserID, EntryDate, Note) On my page i do have a text box for the UserID as well as a Note textbox. When I hite the submit button on my page I am already sending the UserID textbox information to be sent to another table (called RequestTable). However, I am wanting to take that same UserID and insert it into the RequestNote table as well. Let me know if you have any questions for me to further explain anything. **RequestNote**RequestNoteKey (PK) (has identity set to yes)RequestKey (allows nulls)NoteEntryDateEntryUserID (allows Nulls)****This is my stored procedure that I am calling called "NoteInsert"***@Note nvarchar(1000),@EntryUserID nvarchar(50)AS INSERT INTO RequestNote (Note, EntryDate,EntryUserID) VALUES (@Note,GetDate(), @EntryUserID) RETURNGO ****THIS IS THE PAGE THAT CONNECTS THE USER INTERFACE AND STORED PROCEDURE***public static void AddRequestNote(string requestNote, string userID){using (SqlConnection connection = new SqlConnection(connRequestNote)){using (SqlCommand command = new SqlCommand("NoteInsert", connection)){command.CommandType = CommandType.StoredProcedure;command.Parameters.Add(new SqlParameter("@Note", requestNote));command.Parameters.Add(new SqlParameter("@EntryUserID", userID));connection.Open();command.ExecuteNonQuery(); <--THIS IS WHERE I GET AN ERROR THAT SAYS Cannot insert the value NULL into column 'RequestNoteKey', table 'RequestNote'; column does not allow nulls. INSERT fails}
Is there a clever way of reteiving the identity of an INSERT query in SQLServer?
The example below is a the first insert (into the "parent" table with an identity column) of a heirarchical multi-table update.
sqlCommand.CommandText = "INSERT INTO Orders VALUES ( Date, Customer ) ; SELECT @@IDENTITY AS ID" ; sqlCommand.ExecuteNonQuery() ;
The ExecuteNonQuery() method returns the number of rows inserted but I need the ID for the INSERT into the "child" table.
My options based on my current understanding appear to be: a) use command parameters and set ID as an output param b) use a stored procedure, use command parameters and set ID as an output param c) issue the SELECT @@IDENTITY as a subsequent seperate command using ExecuteScalar()
Is there a more elegant way to get the ID using SQLServer's "batch" query mechanism and ADO.NET v1.1? Thanks,
If I call ExecuteNonQuery() in a timer event callback in a console application, it hangs. Why is that?
.B ekiM
class Program { static SqlConnection conn = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=NONEOFYOURBISUINESS;Data Source=localhost");
static void Main(string[] args) { NativeMethods.MEMORYSTATUSEX mem = new NativeMethods.MEMORYSTATUSEX(); NativeMethods.GlobalMemoryStatusEx(mem); Console.WriteLine("{0} bytes", mem.ullAvailPhys);
System.Timers.Timer aTimer = new System.Timers.Timer(); // Set the Interval to 2 seconds (2000 milliseconds). aTimer.Interval = 1000; aTimer.Enabled = true;
// Hook up the Elapsed event for the timer. aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
Console.ReadLine(); }
private static void OnTimedEvent(object source, ElapsedEventArgs e) { NativeMethods.MEMORYSTATUSEX mem = new NativeMethods.MEMORYSTATUSEX(); NativeMethods.GlobalMemoryStatusEx(mem);
SqlCommand cmd = new SqlCommand( "INSERT INTO Observation (StatisticType, StatisticObserved, StatisticValue) VALUES (1, @When, @AvailPhys);" + "INSERT INTO Observation (StatisticType, StatisticObserved, StatisticValue) VALUES (2, @When, @AvailPageFile);" + "INSERT INTO Observation (StatisticType, StatisticObserved, StatisticValue) VALUES (3, @When, @AvailVirtual);" + "INSERT INTO Observation (StatisticType, StatisticObserved, StatisticValue) VALUES (4, @When, @AvailExtendedVirtual);");