Stored Proc Won't Update From C# .NET Code, But Will Update When Testing On Its Own.
Jul 23, 2006
I'm having a strange problem that I can't figure out. I have an SQL stored procedure that updates a small database table. When testing the Stored Procedure from the Server Explorer, it works fine. However, when I run the C# code that's supposed to use it, the data doesn't get saved. The C# code seems to run correctly and the parameters that are passed to the SP seem to be okay. No exceptions are thrown.
ALTER PROCEDURE developers.fort_SaveRedirectURL
(
@accomId int,
@path varchar(250)
)
AS
DECLARE
@enabled bit,
@oldpath varchar(250)
/* Ensure that the accommodation has been enabled */
SELECT @enabled = enabled FROM Experimental_Accommodation
WHERE Experimental_Accommodation.id = @accomId
IF (@enabled = 1)
BEGIN
/* Now check if a path already exists */
SELECT @oldpath = oldpath FROM Experimental_Adpages_Redirect
WHERE Experimental_Adpages_Redirect.accom_id = @accomId
IF @oldpath IS NULL
BEGIN
/* If Path already exists then we should keep the existing URL */
/* Otherwise, we need to insert a new one */
INSERT INTO Experimental_Adpages_Redirect
(oldpath, accom_id)
VALUES (@path,@accomId)
END
END
RETURN
Hello,,,I need to update table but not all fields in stored proc have to be with value (some of fields will be NULL), so i need to avoid updating any field that his parameter with null value.I need the syntax for (IF) statement to optionally update that field.something like this :CREATE PROCEDURE [dbo].[MyUpdate] ( @ID int, @Field1 nvarchar(50), @Field2 nvarchar(50)=null, @Field3 nvarchar(50)=null, @Field4 nvarchar(50) ) AS
UPDATE MyTable SET Field1 = @Field1, if (@Field2<>null) Field2 = @Field2, if (@Field2<>null) Field3 = @Field3, Field4 = @Field4 WHERE ID = @ID I saw example before but i can't remember where. Thank you in advance
I have a stored procedure that updates about a dozen rows.
I have some overloaded functions that I should update different combinations of the rows - 1 function might update 3 rows, another 7 rows.
Do I have to write a stored procedure for each function or I can I handle it in the Stored Procedure. I realise I can have default values but I the default values could overwrite actual data if the values are not supplied but have been previously written.
I wrote a stored proc to be implemented in a datagrid. I went and used it on a record to update some information and it updated THE WHOLE DATABASE WITH THAT ONE RECORD..
IF anyone could shead some light on what I'm doing wrong that would be great.
Hi, I've been reading all sorts of info on the ntext field. I needthis to store xml documents in sql server via a stored proc.Because of its size, I apparently can not use SET (as in UPDATE)therefore I'm trying to do an INSERT of the row with this field (afterdeleting the old row).CREATE PROCEDURE dbo.UpdateXmlWF(@varWO varchar(50)@strWF ntext@varCust varchar(50)@varAssy varchar(50))ASINSERT INTO tblWorkOrders (WorkOrder, Customer, Assy, xmlWF) VALUES(@varWO, @varCust, @varAssy, @strWF)I'm using MSDE so I can't tell what's wrong...it just won't save theproc.PLEASE HELP!Thanks, Kathy
we just moved a database from a shared SQL 2000 server to SQLExpress on a VPS server. Every thing seems to work great, really no performance loss at all, except for one stored proc that is giving us problems. It's function is to update a history table, and then update the production table. On the old server, it would take less than a second to run this, now it takes anywhere from 45 seconds to 1 minute or it times out. This database is used on a classic asp web app. ANY help at all on this would be appreciated as I am pulling my hair out trying to figure out what's wrong here. here is the proc.
------------------------------------------ code ---------------------------------------------- set ANSI_NULLS ON set QUOTED_IDENTIFIER ON SET NOCOUNT ON go
All: I have created a stored procedure on SQL server that does an Insert else Update to a table. The SP starts be doing "IF NOT EXISTS" check at the top to determine if it should be an insert or an update. When i run the stored procedure directly on SQL server (Query Analyzer) it works fine. It updates when I pass in an existing ID#, and does an insert when I pass in a NULL to the ID#. When i run the exact same logic from my aspx.vb code it keeps inserting the data everytime! I have debugged the code several times and all the parameters are getting passed in as they should be? Can anyone help, or have any ideas what could be happening? Here is the basic shell of my SP: CREATE PROCEDURE [dbo].[spHeader_InsertUpdate] @FID int = null OUTPUT,@FLD1 varchar(50),@FLD2 smalldatetime,@FLD3 smalldatetime,@FLD4 smalldatetime AS Declare @rtncode int IF NOT EXISTS(select * from HeaderTable where FormID=@FID) Begin begin transaction --Insert record Insert into HeaderTable (FLD1, FLD2, FLD3, FLD4) Values (@FLD1, @FLD2, @FLD3,@FLD4) SET @FID = SCOPE_IDENTITY(); --Check for error if @@error <> 0 begin rollback transaction select @rtncode = 0 return @rtncode end else begin commit transaction select @rtncode = 1 return @rtncode end endELSE Begin begin transaction --Update record Update HeaderTable SET FLD2=@FLD2, FLD3=@FLD3, FLD4=@FLD4 where FormID=@FID; --Check for error if @@error <> 0 begin rollback transaction select @rtncode = 0 return @rtncode end else begin commit transaction select @rtncode = 2 return @rtncode end End---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
hi need help how to send an email from database mail on row update from stored PROCEDURE multi update but i need to send a personal email evry employee get an email on row update like send one after one email
i use FUNCTION i get on this forum to use split from multi update
how to loop for evry update send an single eamil to evry employee ID send one email
I'm writing a fairly involved stored procedure. In this Stored Procedure, I have an update statement, followed by a select statement. The results of the select statement should be effected by the previous update statement, but its not. When the stored procedure is finish, the update statement seemed to have worked though, so it is working.
I suspect I need something, like a GO statement, but that doesnt seem to work for a stored procedure. Can anyone offer some assistance?
Hey all, I have access as my front end and has upsized to sql server 2000. DLookup function that was in VBA code before was working fine. but after upsizing there is the problem in that code... What could be the alternative for DLookup Function in sql server.. Do i have to write a view or stored procedure..?
Using SQL Server 2005. Writing SQL code but I need to use the reults from two different stored proc. How do you code a select statement using a stored proc. I know when using views you just use the view name in the From or join statemnt, but do you do the same with using a Stored proc. Thank you for your help. David
The problem: I need to validate all stored procedures on my server that they have not been altered after the application has been created.
Our server installation creates the user stored procedures for the application. Once created, I need a way to validate that the proc code has not been altered.
Previously, we were validating against the value of stats_schema_ver and crdate in the sysobjects table for the given stored procedure. During installation we would create a hash value of the crdate and stats_schema_Ver values for all our user defined procs. Then during validation, we would recreate the hash value and compare to that created during installation. If they differed, we knew that the proc code had been altered in some way.
Any alteration of the stored proc would update the stats_schema_ver- if the proc was dropped and recreated, it would update the crdate.
In 2005, the stats_shema_ver value is no longer updated when the proc is altered.
Perhaps this method was completely off-base to begin with...
So, how *does* one verify after installation that no proc code has been altered since installation?
The other option was to create a hash of the proc text definition- but that seems absolutely tedious to rehash the current proc definition every time the proc is accessed. There's also the problem that if you use the "with encryption" directive, it's no longer easy to get the text definition of the proc back out.
Appreciate any general thoughts or specific feedback.
I have a database trigger that is set to call a CLR trigger/stored proc when a certain field in a table is updated. The issue is that if i execute the stored proc manually in enterprise studio, it works perfectly but the same call made through the trigger does not go through. A few more details -
I have CLR integration enabled on the sql server.
The dbo has UNSAFE ASSEMBLY rights
I have the both the assembly and the serialized dll imported in the database.
Here's the definition of the stored proc -
CREATE PROCEDURE [dbo].[WriteXMLNotification]
@TaskID [nvarchar](20)
WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [DataInterfaceWebServices].[TaskUpdateXMLWriter.WriteXMLNotification].[run]
and the trigger -
CREATE TRIGGER [dbo].[tr_Task_U]
ON [dbo].[_Task]
FOR UPDATE, INSERT AS
IF UPDATE (TaskType_Status) OR UPDATE (TaskType) OR UPDATE (TaskType_SubType1)
BEGIN
SET NOCOUNT ON;
DECLARE @status AS INT
DECLARE @taskType AS INT
DECLARE @taskSubType AS INT
DECLARE @taskID as sysname
DECLARE @cmd as sysname
DECLARE @parentTask as sysname
DECLARE @NotificationXMLTaskID as sysname
SELECT @status = [TaskType_Status] FROM inserted
SELECT @taskType = [TaskType] FROM inserted
SELECT @taskSubType = [TaskType_SubType1] FROM inserted
SELECT @taskID = [TaskID] FROM inserted
SELECT @parentTask = [Parent_TaskID] FROM inserted
SELECT @NotificationXMLTaskID = [MCCTaskID] FROM _TaskNotificationXML WHERE [MCCTaskID] = @parentTask
IF (@status = 2602) AND (@taskType = 2282) AND (@taskSubType = 19500)
BEGIN
exec WriteXMLNotification @taskID;
END
ELSE IF (@taskType = 2285) AND (@parentTask IS NOT NULL) AND (@NotificationXMLTaskID IS NOT NULL)
BEGIN
exec WriteXMLNotification @parentTask;
END
END
I stepped into the trigger and it seems to execute the line " exec WriteXMLNotification @taskID;" but nothing happens, but if I run that same line manually, it works. Could it be that the impersonation by the EXECUTE AS clause is causing it to fail?
I am trying to debug sql2000 sp from managed code app with VS.Net 2003 archetect Ed.. It did not stop at the break point within the sql sp. I did granted execute permission for sp_sdidebug. Do I need to attach any process?
Is there anything left off by the article? I referenced msdn article option 2: http://support.microsoft.com/default.aspx?kbid=316549
I'm writing an application using VB 6.0 as the front-end GUI, and theMSDE version of SQL Server as the back-end (it's a program for areally small # of users --- less then 3-4).I'm trying to determine, through the Visual Basic interface, thepermissions of each user that's using the application on his/hermachine.For example, let's say I'm user "Michael" that's sitting down at mymachine using the app. I've written. The security for logging intoSQL Server will be setup using Windows Security (Trusted Connection)as opposed to Windows & SQL Server security. When Michael accesses aparticular form in the VB 6.0 GUI, I want to run some code thatautomatically checks Michael's permission levels on the underlyingtable (actually, a stored procedure supplying the data from the table)that supplies the data to the form he's looking at and then give himsome feedback on the form as to what type of permissions he has whilehe's browsing through the data shown in the form.For example, Michael opens a particular form, code in the backgroundis run to identify that this is Michael accessing the form, the codereturns a value that identifies what type of permissions he has on thedata in the form, and a text box on the form informs Michael (forexample) that he only has read-only permissions to the data he isviewing and cannot edit any of the data.As another example, user Karen sits down at her computer, logs intothe application, opens the same form that Michael just opened, thecode is run in VB to detect the level of permissions she has on thedata being displayed in the form, and the text box on the form informsher that she has editing permissions on the data in the underlyingtable.Etc...If anyone can post an example of the code they use in accomplishingthis task in an application they've written, I'd really appreciate apoint in the right direction or a real-world example that's beenimplemented by one of you. I've written several apps. thus far usingMSDE as the back-end, but the previous apps. I've written were forclients that didn't care about restricting access to theapplication... everyone could pretty much use the application as theydesired and do anything they desired to the data.The current client I'm writing the app. mentioned here for wants tohave security in place to where various users access the applicationwith various levels of permissions to do stuff (or *not* do stuff) tothe data in the application.Thanks very much in advance for any assistance / code provided!Sincerely,Brad McCollumJoin Bytes!
I am trying to use SSIS to update an AS400 DB2 database by calling a stored procedure on the AS400 using an OLE DB command object. I have a select statement running against the SQL Server 2005 that brings back 20 values, all of which are character strings, and the output of this select is piped into the OLE DB command object. The call from SSIS works just fine to pass parameters into the AS400 as long as the stored procedure being called does not have an output parameter defined in its signature. There is no way that I can find to tell the OLE DB command object that one of the parameters is an output (or even an input / output) parameter. As soon as one of the parameters is changed to an output type, I get an error like this:
Code Snippet
Error: 0xC0202009 at SendDataToAs400 1, OLE DB Command [2362]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x8000FFFF.
Error: 0xC0047022 at SendDataToAs400 1, DTS.Pipeline: SSIS Error Code DTS_E_PROCESSINPUTFAILED. The ProcessInput method on component "OLE DB Command" (2362) failed with error code 0xC0202009. The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running. There may be error messages posted before this with more information about the failure.
Error: 0xC0047021 at SendDataToAs400 1, DTS.Pipeline: SSIS Error Code DTS_E_THREADFAILED. Thread "WorkThread0" has exited with error code 0xC0202009. There may be error messages posted before this with more information on why the thread has exited.
Information: 0x40043008 at SendDataToAs400 1, DTS.Pipeline: Post Execute phase is beginning.
Information: 0x40043009 at SendDataToAs400 1, DTS.Pipeline: Cleanup phase is beginning.
Task failed: SendDataToAs400 1
Warning: 0x80019002 at RetrieveDataForSchoolInitiatedLoans: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors raised (3) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
Warning: 0x80019002 at Load_ELEP: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors raised (3) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
SSIS package "Load_ELEP.dtsx" finished: Failure.
I really need to know if the call to the AS400 stored procedure succeeded or not, so I need a way to obtain and evaluate the output parameter. Is there a better way to accomplish what I am trying to do? Any help is appreciated.
I am just trying to capture the return code from a stored proc as follows and if I get a 1 I want the SQL Task to follow a failure(red) constrainst workflow and send a SMTP mail task warning the customer. How do I achieve the Exec SQL Task portion of this, i get a strange error message [Execute SQL Task] Error: There is an invalid number of result bindings returned for the ResultSetType: "ResultSetType_SingleRow".
Using OLEDB connection, I utilize SQL: EXEC ? = dbo.CheckCatLog
EXEC SQL Task Editer settings: RESULTSET: Single Row PARAMETER MAPPING: User::giBatchID DIRECTION: OUTPUT DATATYPE: LONG PARAMETER NAME: 0
PS-Not sure if I need my variable giBatchID which is an INT32 but I thought it is a good idea to feed the output into here just in case there is no way that the EXEC SQL TASK can chose the failure constrainst workflow if I get a 1 returned or success constraint workflow if I get a 0 returned from stored proceedure
CREATE PROCEDURE CheckCatLog @OutSuccess INT AS
-- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON DECLARE @RowCountCAT INT DECLARE @RowCountLOG INT
---these totals should match SELECT @RowCountCAT = (SELECT Count(*) FROM mydb_Staging.dbo.S_CAT) SELECT @RowCountLOG = (SELECT Count(*) FROM mydb_Staging.dbo.S_LOG) --PRINT @RowCountCAT --PRINT @RowCountLOG BEGIN IF @RowCountCAT <> @RowCountLOG --PRINT 'Volume of jobs from the CAT file does not match volume of jobs from the LOG file' --RETURN 1 SET @OutSuccess = 1 END GO
Hi I and using gridview. And binding the data in the code behind.I need to use update command in code behind. How do I achieve this? I protected void lookUP (object sender, EventArgs e) { string strSql, strConn;
System.Text.StringBuilder whereClause = new System.Text.StringBuilder();
Where am I going wrong? I have no idea where to start to look for any incorrect code because it all looks ok! Please help!!! I am entering a record into 5 textboxes - I can see the new record when I open the datagrid view, but when I close the programme and reopen it the record disappears, this code looks ok to me so where is it wrong? Obviously the record is not being written to the database so that when I reopen the programme there is nothing to fill the dataset..........any ideas? Your help is appreciated!!!
Private Sub BtnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSave.Click
In the device emulator when it starts I see two records that were added to the SDF in the VS2008 IDE. I added a third record and after tapping on the Save menu my navigation control shows all three records. I then closed the application. I went to Memory and stopped the form. I went to the File Editor and restarted the application. It only showed the original 2 records. In the File Editor I tapped on the SDF to open it in the Query Analyzer. It also only shows the original two records.
The Dataset appears to be updated, but not the bound table in the SDF. Can any one help? Code is below. bsTEST is the binding SOurce navTEST is my custom Navigation control
Private Sub HandleMenus(ByVal Sender As Object, ByVal EA As EventArgs) Handles mnuAdd.Click, mnuCancel.Click, mnuSave.Click
I am trying to perform a simple update to a SQL Server database table and I can't figure out why this simple UPDATE command doesn't work. I am performing the same thing in another page for owner information and it works just fine. It seems that some of my code won't work even though the syntax is correct and there is no reason for it not to work.
I have hardcoded text for some of the fields and the UPDATE code below works but when I try to use the information that may be in the Textbox, the code won't do the UPDATE. Please help me figure out what is going on.
Thanks
Sub btnUpdate_Click_1(sender As Object, e As EventArgs) Dim UserCode as String Dim PropertyCode as String Dim UnitCode as String Dim address1 as String Dim address2 as String Dim address3 as String Dim city as String Dim zip_Code as String Dim description as String Dim price_Range as String Dim state as String Dim type_Property as String Dim property_Status as String
if chkChangeState.Checked = True then state = ddl_State.SelectedItem.Value else state = lblState.Text end if
if chkPropertyType.Checked = True then type_Property = ddlPropertyType.SelectedItem.Value else type_Property = lblPropertyType.Text end if
if chkPropertyStatus.Checked = True then property_Status = ddlPropertyStatus.SelectedItem.Value else property_Status = lblPropertyStatus.Text end if
Dim connectionString As String = "server='(local)'; trusted_connection=true; database='master'" Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)
Dim queryString As String = "UPDATE [Property_db] SET [Address1]=@Address1, [Address2]=@Address2, [Address3]=@Address3, [City]=@City, [State]=@State, [Zip_Code]=@Zip_Code, [Type_Property]=@Type_Property, [Description]=@Description, [Property_Status]=@Property_Status, [Price_Range]=@Price_Range WHERE ([Property_db].[Code] = @Code) AND ([Property_db].[Prop_Code] = @Prop_Code) AND ([Property_db].[Unit_Code] = @Unit_Code)" Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand dbCommand.CommandText = queryString dbCommand.Connection = dbConnection
Dim dbParam_code As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter dbParam_code.ParameterName = "@Code" dbParam_code.Value = UserCode dbParam_code.DbType = System.Data.DbType.String dbCommand.Parameters.Add(dbParam_code) Dim dbParam_prop_Code As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter dbParam_prop_Code.ParameterName = "@Prop_Code" dbParam_prop_Code.Value = PropertyCode dbParam_prop_Code.DbType = System.Data.DbType.String dbCommand.Parameters.Add(dbParam_prop_Code) Dim dbParam_unit_Code As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter dbParam_unit_Code.ParameterName = "@Unit_Code" dbParam_unit_Code.Value = UnitCode dbParam_unit_Code.DbType = System.Data.DbType.String dbCommand.Parameters.Add(dbParam_unit_Code) Dim dbParam_address1 As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter dbParam_address1.ParameterName = "@Address1" dbParam_address1.Value = txtAddress1.Text dbParam_address1.DbType = System.Data.DbType.String dbCommand.Parameters.Add(dbParam_address1) Dim dbParam_address2 As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter dbParam_address2.ParameterName = "@Address2" dbParam_address2.Value = txtAddress2.Text dbParam_address2.DbType = System.Data.DbType.String dbCommand.Parameters.Add(dbParam_address2) Dim dbParam_address3 As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter dbParam_address3.ParameterName = "@Address3" dbParam_address3.Value = txtAddress3.Text dbParam_address3.DbType = System.Data.DbType.String dbCommand.Parameters.Add(dbParam_address3) Dim dbParam_city As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter dbParam_city.ParameterName = "@City" dbParam_city.Value = txtCity.Text dbParam_city.DbType = System.Data.DbType.String dbCommand.Parameters.Add(dbParam_city) Dim dbParam_state As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter dbParam_state.ParameterName = "@State" dbParam_state.Value = state dbParam_state.DbType = System.Data.DbType.String dbCommand.Parameters.Add(dbParam_state) Dim dbParam_zip_Code As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter dbParam_zip_Code.ParameterName = "@Zip_Code" dbParam_zip_Code.Value = txtZipCode.Text dbParam_zip_Code.DbType = System.Data.DbType.String dbCommand.Parameters.Add(dbParam_zip_Code) Dim dbParam_type_Property As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter dbParam_type_Property.ParameterName = "@Type_Property" dbParam_type_Property.Value = type_Property dbParam_type_Property.DbType = System.Data.DbType.String dbCommand.Parameters.Add(dbParam_type_Property) Dim dbParam_description As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter dbParam_description.ParameterName = "@Description" dbParam_description.Value = txtDescription.Text dbParam_description.DbType = System.Data.DbType.String dbCommand.Parameters.Add(dbParam_description) Dim dbParam_property_Status As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter dbParam_property_Status.ParameterName = "@Property_Status" dbParam_property_Status.Value = property_Status dbParam_property_Status.DbType = System.Data.DbType.String dbCommand.Parameters.Add(dbParam_property_Status) Dim dbParam_price_Range As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter dbParam_price_Range.ParameterName = "@Price_Range" dbParam_price_Range.Value = txtPriceRange.Text dbParam_price_Range.DbType = System.Data.DbType.String dbCommand.Parameters.Add(dbParam_price_Range)
Dim rowsAffected As Integer = 0 dbConnection.Open Try rowsAffected = dbCommand.ExecuteNonQuery Finally dbConnection.Close End Try
'if Not rowsAffected then Response.Redirect("./editproperty.aspx") 'end if End Sub
Not sure what happened to my post, it seems to have disappeared. Here we go again. I have a stored procedure that I would like some feedback on, as I feel it may be inefficient as coded:
@ZUserID varchar(10) AS SET NOCOUNT ON
DECLARE @counter int SET @counter = 0 WHILE @counter < 10 BEGIN SET @counter = @counter + 1 IF EXISTS(SELECT * FROM tblWork WHERE UserID = @ZUserID And LineNumber = @counter) BEGIN UPDATE tblWork SET TransID = Null, TransCd = Null, InvoiceNo = Null, DatePaid = Null, Adjustment = Null, Vendor = Null, USExchRate = Null WHERE UserID = @ZUserID And LineNumber = @counter END ELSE INSERT INTO tblWork (LineNumber,TransCd,UserID) VALUES (@counter,'P',@ZUserID) END
C#, Webforms, VS 2005, SQL Hi all, quick hit question. I'm trying to update a table with an employee name and hire date. Session variable of empID, passed from a previous page (successfully) determines which row to plop the update into. It's not working even though i compiles and makes it all the way through the code to the txtReturned.Text = "I made it" debug line...Any thoughts? 1 string szInsSql; 2 3 string sConnectionString = "Data Source=dfssql;Database=MyDB;uid=myID;pwd=myPWD"; 4 SqlConnection objConn = new SqlConnection(sConnectionString); 5 6 objConn.Open(); 7 8 szInsSql = "UPDATE empEmployee SET " + 9 "Name = '" + this.txtName.Text + "', " + 10 "HireDate = '" + this.txtHireDate.Text + "', " + 11 "WHERE empID = '" + Session[empID] + "'"; 12 13 SqlCommand objCmd1 = new SqlCommand(szInsSql, objConn); 14 objCmd1.ExecuteNonQuery(); 15 16 txtReturned.Text = "I made it"; It's got to be a ' or a , out of place but I've looked at this code for a half hour straight, trying a variety of changes...and it still doesn't update the DB...Any help would be great. Thank you! -Corby-
Hi all My error is as follows: Incorrect syntax near '('.Line 27: acceptOrDeclineFriendship.UpdateParameters.Add("Response", answer)Line 28: acceptOrDeclineFriendship.UpdateParameters.Add("FriendID", friend_id)Line 29: acceptOrDeclineFriendship.Update()Line 30: Line 31: End Sub Bear with me... I have a page where i use a repeater control to list users who have requested to be friends with the currently online user. The 'getFriendRequests' query looks like this: SelectCommand="SELECT * FROM Friends, UserDetails WHERE (Friends.UserID = UserDetails.UserID) AND (FriendID = @UserID) AND (ApprovedByFriend = 'False') ORDER BY Friends.Requested DESC">This works. Within each repeater template, there are 2 buttons, 'Accept' or 'Decline', like this: <asp:Repeater ID="Repeater1" runat="server" DataSourceID="getFriendRequests"> <ItemTemplate> (other stuff like avatar and username etc) <asp:Button ID="accept" runat="server" Text="Accept" commandName="Accept" commandArgument='<%#Eval("UserID")%>' onCommand="Accept_Decline_Friends"/> <asp:Button ID="decline" runat="server" Text="Decline" commandName="Decline" commandArgument='<%#Eval("UserID")%>' onCommand="Accept_Decline_Friends"/> </ItemTemplate> </asp:Repeater> The code-behind (VB) which deals with this is as follows: Protected Sub Accept_Decline_Friends(ByVal sender As Object, ByVal e As CommandEventArgs)
'retrieve id of requestee and the answer accept/decline Dim friend_id As String = e.CommandArgument.ToString Dim answer As String = e.CommandName.ToString
'add the parameters acceptOrDeclineFriendship.UpdateParameters.Add("Response", answer) acceptOrDeclineFriendship.UpdateParameters.Add("FriendID", friend_id) acceptOrDeclineFriendship.Update()
End Sub Since the buttons are being created dynamically, this is how i track 1. the response from the currently logged in user 'Accept/Decline' and 2. who they are responding to (by their uniqueid) This relates to a sqlDataSource on my .aspx page like this: <!---- update query when user has accepted the friendship ----> <asp:SqlDataSource ID="acceptOrDeclineFriendship" runat="server" ConnectionString="<%$ xxx %>" UpdateCommand="UPDATE Friends SET (ApprovedByFriend = @Response) WHERE (FriendID = @UserID) AND (UserID = @FriendID)"> <UpdateParameters> <asp:ControlParameter Name="UserID" ControlID="userIdValue" /> </UpdateParameters> </asp:SqlDataSource> Which is meant to update my 'Friends' table to show that 'ApprovedByFriend' (the logged in user) is either 'Accept' or 'Decline', and record who's request was responded to. I hope this is clear, just trying to suppy all of the information! The error appears to be saying that I have an issue with my code-behind, where i am telling the sqlDataSource above to UPDATE. What I can say is that for each button in the repeater, the 2 variables 'friend_id' and 'answer' are picking up the correct values. Can anyone see any obvious problems here? Any help is very much appreciated as i am well and truley stuck!
hi there, i have been wrestling with this for quite a while, as in my other post http://forums.asp.net/t/1194975.aspx, what someone advised me was to put in try catch blocks ot see whats going on, problem is i have never really done it whit this kinda thing before, and i was wondering if someone could point me in the right direction.
For example where would i put the try catch block in here, to show me if its not working public int getLocationID(int ProductID, int StockLoc) { // Gets the LocationID (Shelf ID?) for the stock column and product id // passed // The SQL will look Something like: string strSQL; strSQL = "SELECT " + " location" + StockLoc + " " + "FROM " + " tbl_stock_part_multi_location " + "WHERE " + " stock_id = " + ProductID;string sConnectionString = "Data Source=xxxxx;Initial Catalog=xxxx;User ID=xxxx;Password=xxxxx"; SqlConnection objConnGetLocationID = new SqlConnection(sConnectionString);SqlCommand sqlCmdGetLocationID = new SqlCommand(strSQL, objConnGetLocationID); objConnGetLocationID.Open();int intLocation = Convert.ToInt32(sqlCmdGetLocationID.ExecuteScalar()); return intLocation; }
Is there any way I can use a variable from my code behind file in the UpdateCommand of a sqlDataSource? I have tried <%$ strUserGuid %>and<% strUserGuid %> any help appreciated.Thanks Dave
I have dataadapter and dataset that reads/writes to SQL tables. I can read. I can create "new" records. However, I have not been able to master the "updating" of an existing row. Can someone provide me specific code for doing this please or tell me what I doing wrong in the code below. The code I using is below. I don't get error, but changes do not get written to SQL dbase. For starters, I think I "not" supposed to use the 2nd line(....NewRow). I think this is only for new row, not updating of existing row - but I don't know any other way to get schema of row. thanks to any who can help
Hi all I have a GridView on an aspx page, that is enabled for editing, deletion and sorting. In the Page_Load event of the aspx page, i add a SqlDataSource to the page, and bind the source to the GridView. When i click the update, or delete button, it makes a PostBack, but nothing is affected. I'm sure this has got something to do with the parameters. First, i tried having the GridView.AutoGenerateColumns set to True. I have also tried adding the columns manually, but no affect here either. The code for setting the commands, and adding the SqlDataSource to the page are as follows: string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; string strProvider = ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName; string selectCommand = "SELECT * FROM rammekategori"; SqlDataSource ds = new SqlDataSource(strProvider, strConn, selectCommand); ds.ID = "RammeKategoriDS"; ds.UpdateCommand = "UPDATE rammekategori SET Kategoribeskrivelse = @Kategoribeskrivelse WHERE (Kategorinavn = @Kategorinavn)"; ds.DeleteCommand = "DELETE FROM rammekategori WHERE (Kategorinavn = @Kategorinavn)"; Parameter Kategorinavn = new Parameter("Kategorinavn", TypeCode.String); Parameter Kategoribeskrivelse = new Parameter("Kategoribeskrivelse", TypeCode.String); ds.UpdateParameters.Add(Kategorinavn); ds.UpdateParameters.Add(Kategoribeskrivelse); ds.DeleteParameters.Add(Kategorinavn); Page.Controls.Add(ds); SqlDataSource m_SqlDataSource = Page.FindControl("RammeKategoriDS") as SqlDataSource; if (m_SqlDataSource != null) { this.gvRammeKategorier.DataSourceID = m_SqlDataSource.ID; } As mentioned - no affect at all! Thanks in advance - MartinHN