Showing posts with label executenonquery. Show all posts
Showing posts with label executenonquery. Show all posts

Monday, March 19, 2012

ExecuteNonQuery: Connection property has not been initialized

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)

Dim result As Int32
Dim cmd As OdbcCommand

cmd = new OdbcCommand( "(? = CALL CheckUserExists(?))", db_conn )
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add( "result", OdbcType.Int ).Direction =
ParameterDirection.ReturnValue

cmd.Parameters.Add( "@.userName", OdbcType.VarChar, 100 ).Value =
Request.Form("userName")

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

end Sub

</script
<html><body>
<form runat="server">
<asp:TextBox id=userName runat="server" />
<asp:Button id=CheckButton runat="server" Text="Check Username"
onClick="CheckButton_Click" /
<p>
<asp:Label id=CheckResults runat=server />
</form>
</body></html>
--

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

Thank You,
Jason WilliardHi Jason,

To me it seems that you are still using asp type techniques of data access. You will have to initate your dbconnection object before you can actually use any database related functions.

With your code you are missing ofdb_conn variable. Which I am presuming that you have in include file, but this will not work with asp.net.

HTH|||It's looks like your maye be geeting error because of following reason.

1.Your connection string is not correct or not open as we can't see when and where it was intialize/open .
2.check your store procdure and see if you are passing correct parameter,correct typen etc.
3.In your code it looks likes may be you have open your connection in db_access.inc but i don't think it's good approach .you should open the connection in same sub and close as soon as you you finished.Or if you want to write neat and clean code and also don't want to wire same code agaian then create data layer class where you can perform all the database realted operation.

Arvind Malik|||I made some changes to the page so that the db connection is all done from within the Sub. Below are the code changes that I made:

--
Sub CheckButton_Click(Sender as Object, e as EventArgs)

Dim db_conn_str As String
Dim db_conn As OdbcConnection
Dim resultAs Int32
Dim cmdAs OdbcCommand
Dim context_dsn_nameAs String = "adwarefilter"

db_conn_str = "dsn=" & context_dsn_name & ";"
db_conn = New OdbcConnection( db_conn_str )
db_conn.Open()

cmd = new OdbcCommand( "(? = CALL CheckUserExists(?))", db_conn )
cmd.CommandType = CommandType.StoredProcedure
--

Now I am getting a new error message:

--
Exception Details: System.Data.Odbc.OdbcException: ERROR [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Line 1: Incorrect syntax near '='.

Source Error:

Line 28: cmd.Parameters.Add( "@.username", OdbcType.VarChar, 100 ).Value = Request.Form("userName")
Line 29:
Line 30: cmd.ExecuteNonQuery()
--

Any suggestions?|||What is this query: "(? = CALL CheckUserExists(?))", ? Where is the SQL Query?

Brian|||This is a call to a Stored Procedure. The SQL query is within the Stored Proc.|||I am pretty sure that your stored procedure call should look like this:


cmd = new OdbcCommand( "{CALL CheckUserExists(?)}", db_conn )

Note that I made these changes:
-- removed the question mark (?) and the equal sign (=)
-- changed a set of parentheses to a set of curly braces

But, I have a question -- why oh why are you using the System.Data.Odbc class instead of System.Data.SqlData? Are you using SQL Server 7?

Terri|||Actually, I hadn't noticed you are using a ReturnValue, sorry!! The question mark and equal sign can remain. The problem is likely just the use of parentheses instead of curly braces.


cmd = new OdbcCommand( "{? =CALL CheckUserExists(?)}", db_conn )

Terri

ExecuteNonQuery() not giving correct affected rows

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 -1

ALTER PROCEDURE [dbo].[SP_AddObjectContribution]
@.ObjectId int,
@.FanId int,
@.DateContributed DateTime,
@.Notes nvarchar(512),
@.ObjectType int
AS

BEGIN

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 TRAN

END

-- Without if/else ExecuteNonQuery returns 1

ALTER 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

COMMIT TRAN

END

1ALTER PROCEDURE [dbo].[SP_AddObjectContribution]2 @.ObjectIdint,3 @.FanIdint,4 @.DateContributedDateTime,5 @.Notesnvarchar(512),6 @.ObjectTypeint7AS89BEGIN1011 BEGIN TRAN12 IF @.ObjectType = 213BEGIN14 INSERT INTO FighterContributions15 (FighterId, FanId, DateContributed, Notes)VALUES16 (@.ObjectId, @.FanId, @.DateContributed, @.Notes)17RETURN@.@.ROWCOUNT18END1920END212223
Try each statement like this
|||

RETURN @.@. ROWCOUNT on each statement won't work because it won't commit the transaction (it won't hit COMMIT TRAN).

|||

Perhaps you can add an OUTPUT Parameter to get the rows affected. Instead of this statement: IF @.@.ERROR <> 0, try:

SELECT @.rows = @.@.ROWCOUNT, @.Error = @.@.ERROr

IF @.ERROR <> 0

You will have to declare the @.Rows and @.Error variables. Add @.Rows to the parameters list as OUTPUT param. Check the value in @.rows from your front end.

|||

I think only one insert statment will execute at one time based on parameter.. don;t kwno why u are using transaction for single insert. ? Is this correctSurprise

|||

I'm sorry guys. I think I messed up while testing the method because right now the stored procedure in question is now working. I also added RETURN SCOPE_IDENTITY() to get the ID of the new inserted record and it works. So having INSERT statements inside IF ELSE is not a problem for executenonquery.

So this is the final procedure

ALTER PROCEDURE [dbo].[SP_AddObjectContribution]
@.ObjectId int,
@.FanId int,
@.DateContributed DateTime,
@.Notes nvarchar(512),
@.ObjectType int
AS
BEGIN
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 TRAN

RETURN SCOPE_IDENTITY()

END

For those who are interested, here is how to get the value of the new id. Ignore CreateParameter() method. It is just an abstraction.

IDataParameter param = CreateParameter("ReturnValue", DbType.Int32);
param.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(param);
connection.Open();
if (command.ExecuteNonQuery() > 0)
{
newObjectId = (int)((IDataParameter)command.Parameters["ReturnValue"]).Value;
}

|||

satya_tanwar:

I think only one insert statment will execute at one time based on parameter.. don;t kwno why u are using transaction for single insert. ? Is this correctSurprise

Actually, I am going to add delete statements before the insert statements later. Anyways, thanks for helping out.

|||

thats good mark the post as answered and close the post

ExecuteNonQuery while dataReader still open

Hi all!

I basically need to get some records from a table and while looping through them i need to insert some records on other table.

I keep getting this error:

There is already an open DataReader associated with this connection which must be closed first.

The piece of code that I have is like this:


...
SqlCommand sqlCmd2 = new SqlCommand(sqlString2, dbConn);
sqlCmd2.Transaction = trans;
SqlDataReader dr = sqlCmd2.ExecuteReader(CommandBehavior.CloseConnection);

//loop through dr
while (dr.Read())
{
string sqlStr = "insert into prodQtyPrice (typeQtyId, prodId, typeId) values(28," + dr["prodId"] + "," + dr["typeId"] +")";
SqlCommand sqlCmd3 = new SqlCommand(sqlStr, dbConn);
//sqlCmd3.Transaction = trans;
sqlCmd3.ExecuteNonQuery();
}
...

Also I would like to have the insertions in the same transaction as the previous sql commands.

Thanks a million!

LAMwhy don't you just do that in a procedure? It looks like it's a simple select then insert right?

Insert Into ProdQtyPrice ( typeQtyId, prodId, typeId )
VALUES
SELECT 28, prodID, TypeID From WhereverYouGetThisFrom

GO|||First of all, thanks for answering so fast!

The main reason that is not inside a storedProcedure is requirements. The entire app is not using SP and this has to be done the same way.

LAM|||>>The entire app is not using SP

looks like you have bigger prbs to worry about.
anyway, to answer your q, since the connection is already open with the datareader, you need to open another connection to do the insert.

hth|||you all are making me cross.

command.CommandText = "Insert Into ProdQtyPrice ( typeQtyId, prodId, typeId ) VALUES SELECT 28, prodID, TypeID From WhereverYouGetThisFrom";

ExecuteNonQuery to count number of rows?

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 myCommandAs New SqlClient.SqlCommandmyCommand.CommandText ="ap_Select_ModelRequests_RequestDateTime"myCommand.CommandType = CommandType.StoredProceduremyCommand.Parameters.AddWithValue("@.selectDate", dateEntered)myCommand.Parameters.AddWithValue("@.selectCountry",CInt(selectCountry))myCommand.Connection = concon.Open()Dim rowCountAs Integer = myCommand.ExecuteNonQuery()numberParts.Text = rowCount.ToStringcon.Close()
Thank you.

Check yourap_Select_ModelRequests_RequestDateTimestored procedure, and if you find:

SET NOCOUNT OFF

useually at the end of SP, remove it and I hope this will work.

Good luck.

|||

Hi SolitaryMan,

Normally one would use ExecuteReader for SELECT statements, which you seem to be doing, and call sqlDataReader.RecordsAffected to get the number of rows affected.

Getting -1 from ExecuteNonQuery for a SELECT statement is documented behavior:

"For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1." --http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(VS.71).aspx

As for passing parameters to a stored proceudre with ExecuteNonQuery, that should not affect the return value. ExecuteNonQuery does indeed return the number of rows affected, just not for SELECT statements for example.

Here's some sample code for using SqlDataReader to get the number of rows affected from a SELECT Statement:

SqlCommand selectStatement =newSqlCommand();

selectStatement.CommandText ="PROC_SELECT_ITEM";

selectStatement.CommandType =CommandType.StoredProcedure;

selectStatement.Connection = connection;

SqlDataReader reader = selectStatement.ExecuteReader();

int rowsAffected = reader.RecordsAffected;

Pete

|||

You can use @.@.ROWCOUNT in your stored procedure and assign it to an output parameter.

|||

Peter Lee:

Hi SolitaryMan,

Normally one would use ExecuteReader for SELECT statements, which you seem to be doing, and call sqlDataReader.RecordsAffected to get the number of rows affected.

Getting -1 from ExecuteNonQuery for a SELECT statement is documented behavior:

"For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1." --http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(VS.71).aspx

As for passing parameters to a stored proceudre with ExecuteNonQuery, that should not affect the return value. ExecuteNonQuery does indeed return the number of rows affected, just not for SELECT statements for example.

Here's some sample code for using SqlDataReader to get the number of rows affected from a SELECT Statement:

SqlCommand selectStatement =newSqlCommand();

selectStatement.CommandText ="PROC_SELECT_ITEM";

selectStatement.CommandType =CommandType.StoredProcedure;

selectStatement.Connection = connection;

SqlDataReader reader = selectStatement.ExecuteReader();

int rowsAffected = reader.RecordsAffected;

Pete

Hi Pete.

What you wrote is correct, but I do not think it will work if the stored procedure has a SET NOCOUNT OFF?

Thanks.

|||

Hi CS4Ever,

Thanks. You are right, you cannot have the SET NOCOUNT in the stored procedure.

In any case, you do not typically use ExecuteNonQuery to execute a SELECT statement, especially if you want to know how many rows are retrieved.

So both suggestions are indeed valid, with the resulting suggestion being to use an ExecuteReader with a stored procedure without the SET NOCOUNT statement.

Pete

|||

Peter Lee:

Hi CS4Ever,

Thanks. You are right, you cannot have the SET NOCOUNT in the stored procedure.

In any case, you do not typically use ExecuteNonQuery to execute a SELECT statement, especially if you want to know how many rows are retrieved.

So both suggestions are indeed valid, with the resulting suggestion being to use an ExecuteReader with a stored procedure without the SET NOCOUNT statement.

Pete

You are right.

Thanks Pete.

ExecuteNonQuery syntax

Hi, I am trying to execute a nonquery as follows (look for bold):

Dim connStringSQLAsNew SqlConnection("Data Source=...***...Trusted_Connection=False")

'// Create the new OLEDB connection to Indexing Service

Dim connIndAsNew System.Data.OleDb.OleDbConnection(connStringInd)

Dim commandIndAsNew System.Data.OleDb.OleDbDataAdapter(strQueryCombined, connInd)

Dim commandSQLAsNew SqlCommand("GetAssetList2", connStringSQL)

commandSQL.CommandType = Data.CommandType.StoredProcedure

Dim resultDSAsNew Data.DataSet()

Dim resultDAAsNew SqlDataAdapter()

'// Fill the dataset with values

commandInd.Fill(resultDS)

'// Get the XML values of the dataset to send to SQL server and run a new query

...

'// Return the number of results

resultCount.Text = source.Count.ToString

results.DataSource = source

results.DataBind()

'// Record the search

commandSQL =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.Text

commandSQL.Parameters.Add("@.searchString", Data.SqlDbType.VarChar, 1000).Value = searchText.Text

connStringSQL.Open()

commandSQL.ExecuteNonQuery()

connStringSQL.Close()

The stored procedure looks like this:

Use GTGAssets

DROPPROC dbo.RecordSearch;

--New Procedure

GO

CREATEPROC dbo.RecordSearch

(

@.userNamevarchar(50),

@.createdDateTimeDateTime,

@.numRowsvarchar(1000),

@.searchStringvarchar(1000)

)

AS

BEGIN

SETNOCOUNTON

INSERTINTO SearchLog(SearchString, CreatedByUser, CreatedDTTM, RowsReturned)VALUES(@.searchString, @.userName, @.createdDateTime, @.numRows)

END

GO

Any 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.TextLine 170: connStringSQL.Open()Line 171: commandSQL.ExecuteNonQuery()Line 172: connStringSQL.Close()Line 173: End If

Many thanks!

James

Alright, I found this - it's the way the DateTime is being passed in. The DateTime parameter for the last command looks like this:

#9/11/2006 4:01:25 PM#


However, when this procedure is run on SQL Server Query Analyzer:

USE [GTGAssets]
GO

DECLARE @.return_value int

EXEC @.return_value = [dbo].[RecordSearch]
@.userName = N'name',
@.createdDateTime = N'#9/11/2006 4:01:25 PM#',
@.numRows = N'10',
@.searchString = N'soa'

SELECT 'Return Value' = @.return_value

GO


I get this SQL Server error. I tried this insert (notice the lack of pound signs) it actually works.

USE [GTGAssets]
GO

DECLARE @.return_value int

EXEC @.return_value = [dbo].[RecordSearch]
@.userName = N'CVNS\JFogarty',
@.createdDateTime = N'9/11/2006 4:01:25 PM',
@.numRows = N'10',
@.searchString = N'soa'

SELECT 'Return Value' = @.return_value

GO


Why is this? The pound signs should not be added to the DateTime.Now(), should it?

Thanks!|||You need to enclose date with #'s for Access DB not SQL Server.|||

Well the problem is that VB.Net automattical adds the # - this is the code:

commandSQL.Parameters.Add("@.createdDateTime", Data.SqlDbType.DateTime).Value = DateTime.Now()

|||AFAIK it shouldnt be putting any #'s.|||You forgot to set the commandtype

ExecuteNonQuery requires an open and available Connection

Using SQL 2000 Developer, Windows XP, and DotNet 2.0 I get this error
message when trying to UPDATE a very large table:
"ExecuteNonQuery requires an open and available Connection. The connection's
current state is closed."
The UPDATE command affects all the rows in the column. The confusing part
is - it only occurs on a very large table (over 1M rows). It does not orrur
on smaller tables. So I don't think it actually has anything to do with the
connection.
Any ideas would be greatly appreciated.Just a guess, the connection might have timed out or broken. Try increasing
the timeout
"Neil W." wrote:

> Using SQL 2000 Developer, Windows XP, and DotNet 2.0 I get this error
> message when trying to UPDATE a very large table:
> "ExecuteNonQuery requires an open and available Connection. The connection
's
> current state is closed."
> The UPDATE command affects all the rows in the column. The confusing part
> is - it only occurs on a very large table (over 1M rows). It does not orr
ur
> on smaller tables. So I don't think it actually has anything to do with t
he
> connection.
> Any ideas would be greatly appreciated.
>
>
>|||Neil W. (neilw@.NOSPAMTHANKYOUnetlib.com) writes:
> Using SQL 2000 Developer, Windows XP, and DotNet 2.0 I get this error
> message when trying to UPDATE a very large table:
> "ExecuteNonQuery requires an open and available Connection. The
> connection's current state is closed."
> The UPDATE command affects all the rows in the column. The confusing
> part is - it only occurs on a very large table (over 1M rows). It does
> not orrur on smaller tables. So I don't think it actually has anything
> to do with the connection.
Might be so, but I would put my bets on the ADO .Net code. How does
the relevant bits look like.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

ExecuteNonQuery not returning rows affected

I was racking my brains trying to figure out why SomeCommand.ExecuteNonQuery() was not returning any rows...

SQL Server 2005 likes to put theSET 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.

Thanks for your help...

But can u tell me what is the use of SET NOCOUNT ON ?

|||You use it to suppress the counts of records affected in your stored procedure. There must also always be a resultset that is returned for each such message. By turning nocount on, then the records affected counts aren't transferred to the client, and empty resulsets are discarded.

ExecuteNonQuery in SQL 2005

I have an ASP.Net page that runs the following command which is giving me
the following SQL error:
The statement has been terminated.
Subquery returned more than 1 value. This is not permitted when the subquery
follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The code in the page is as follows:
strSQL = "EXEC fd_insFileTaskDefaultsNew " & lngNextFile & ", " &
Request.Form("cboFileTypeID") & ", 0"
cmd = New OleDbCommand(strSQL, conFileData)
lngRows = cmd.ExecuteNonQuery()
It is failing on the last statement and I don't know why. Also, below is
the stored proc code. Can anyone help? Thanks
David
CREATE PROCEDURE dbo.fd_insFileTaskDefaultsNew
(
@.FileNumber int,
@.FileTypeID int,
@.Rows int output
)
AS
/* SET NOCOUNT ON */
INSERT INTO FileTasks
(FileNumber, TaskTitle, TaskDate, PrimaryID, NotifyDate, TaskNotes,
AssignedID)
SELECT @.FileNumber, TaskTitle,
DATEADD(day, TaskDaysOut, GETDATE()), PrimaryID,
CONVERT(char(10), GETDATE(), 101), TaskNotes, AssignedID
FROM FileTaskDefaults
WHERE FileTypeID = @.FileTypeID
RETURN @.RowsTry executing the stored procedure directly from query analyzer and see if
you get the same error?
"David" <dlchase@.lifetimeinc.com> wrote in message
news:uQdZVqTbGHA.1204@.TK2MSFTNGP04.phx.gbl...
> I have an ASP.Net page that runs the following command which is giving me
> the following SQL error:
> The statement has been terminated.
> Subquery returned more than 1 value. This is not permitted when the
subquery
> follows =, !=, <, <= , >, >= or when the subquery is used as an
expression.
> The code in the page is as follows:
> strSQL = "EXEC fd_insFileTaskDefaultsNew " & lngNextFile & ", " &
> Request.Form("cboFileTypeID") & ", 0"
> cmd = New OleDbCommand(strSQL, conFileData)
> lngRows = cmd.ExecuteNonQuery()
> It is failing on the last statement and I don't know why. Also, below is
> the stored proc code. Can anyone help? Thanks
> David
>
> CREATE PROCEDURE dbo.fd_insFileTaskDefaultsNew
> (
> @.FileNumber int,
> @.FileTypeID int,
> @.Rows int output
> )
> AS
> /* SET NOCOUNT ON */
> INSERT INTO FileTasks
> (FileNumber, TaskTitle, TaskDate, PrimaryID, NotifyDate, TaskNotes,
> AssignedID)
> SELECT @.FileNumber, TaskTitle,
> DATEADD(day, TaskDaysOut, GETDATE()), PrimaryID,
> CONVERT(char(10), GETDATE(), 101), TaskNotes, AssignedID
> FROM FileTaskDefaults
> WHERE FileTypeID = @.FileTypeID
> RETURN @.Rows
>|||Yes, same error.
David
"Jim Underwood" <james.underwoodATfallonclinic.com> wrote in message
news:uqtyUzTbGHA.3992@.TK2MSFTNGP05.phx.gbl...
> Try executing the stored procedure directly from query analyzer and see if
> you get the same error?
> "David" <dlchase@.lifetimeinc.com> wrote in message
> news:uQdZVqTbGHA.1204@.TK2MSFTNGP04.phx.gbl...
> subquery
> expression.
>|||Is FileTaskDefaults a view?
Are there any triggers on FileTasks?
David
"David" <dlchase@.lifetimeinc.com> wrote in message
news:ugsFP3TbGHA.504@.TK2MSFTNGP03.phx.gbl...
> Yes, same error.
> David
> "Jim Underwood" <james.underwoodATfallonclinic.com> wrote in message
> news:uqtyUzTbGHA.3992@.TK2MSFTNGP05.phx.gbl...
>|||It doesn't look to me that your output parameter is ever assigned to
any value. Don't you need something like this
SELECT @.FileNumber, TaskTitle,
DATEADD(day, TaskDaysOut, GETDATE()), PrimaryID,
CONVERT(char(10), GETDATE(), 101), TaskNotes, AssignedID
FROM FileTaskDefaults
WHERE FileTypeID = @.FileTypeID
-- assign row count to @.Rows
SELECT @.Rows = @.@.Rowcount|||> RETURN @.Rows
Where does this value get populated? Do you want to use a RETURN, OUTPUT,
or both? I suggest sticking to output parameters for this kind of data, and
not using RETURN. RETURN is meant to return a status code (e.g.
success/failure), not data. This is one of the reasons they're limited to
INTeger datatypes.
A|||That was it! I removed the trigger and it worked. Thank you.
David
"David Browne" <davidbaxterbrowne no potted meat@.hotmail.com> wrote in
message news:%23%236acDUbGHA.4912@.TK2MSFTNGP05.phx.gbl...
> Is FileTaskDefaults a view?
> Are there any triggers on FileTasks?
> David
> "David" <dlchase@.lifetimeinc.com> wrote in message
> news:ugsFP3TbGHA.504@.TK2MSFTNGP03.phx.gbl...
>|||> That was it! I removed the trigger and it worked. Thank you.
I don't see how that is possible, unless either
(a) you didn't post all of the stored procedure code in your original post,
or
(b) you eliminated the error, but you aren't actually verifying that the
stored procedure is correctly returning the rowcount.
Anyway, it sounds like your trigger was written expecting only single-row
row modifications. You should re-visit that logic instead of just throwing
the trigger away, especially if the trigger is not yours and you are not
sure what it was doing.|||David (dlchase@.lifetimeinc.com) writes:
> That was it! I removed the trigger and it worked. Thank you.
And the trigger did not serve any purpose? Yeah, maybe it was just an
old relic, but I get nervous when I hear things like this. Just because
you did not get any error message, does not mean that it worked. If you
removed a trigger that performed some important task to maintain database
integrity, I would not call that working...
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||hopefully the OP removed to trigger temporarily just to confirm that was the
issue and is rewriting the trigger to correct the subquery.
"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns97B6D62F991A4Yazorman@.127.0.0.1...
> David (dlchase@.lifetimeinc.com) writes:
> And the trigger did not serve any purpose? Yeah, maybe it was just an
> old relic, but I get nervous when I hear things like this. Just because
> you did not get any error message, does not mean that it worked. If you
> removed a trigger that performed some important task to maintain database
> integrity, I would not call that working...
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx

ExecuteNonQuery hangs in Timer event notification

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);\n" +
"INSERT INTO Observation (StatisticType, StatisticObserved, StatisticValue) VALUES (2, @.When, @.AvailPageFile);\n" +
"INSERT INTO Observation (StatisticType, StatisticObserved, StatisticValue) VALUES (3, @.When, @.AvailVirtual);\n" +
"INSERT INTO Observation (StatisticType, StatisticObserved, StatisticValue) VALUES (4, @.When, @.AvailExtendedVirtual);\n");

DateTime dt = DateTime.Now;
cmd.Parameters.AddWithValue("AvailPhys", mem.ullAvailPhys);
cmd.Parameters.AddWithValue("AvailPageFile", mem.ullAvailPageFile);
cmd.Parameters.AddWithValue("AvailVirtual", mem.ullAvailVirtual);
cmd.Parameters.AddWithValue("AvailExtendedVirtual", mem.ullAvailExtendedVirtual);
cmd.Parameters.AddWithValue("When", dt);

cmd.ExecuteNonQuery();

Console.WriteLine("Inserted {0}", dt);
}

}

A-hah! It's not hanging; it's just throwing an exception that the runtime itself catches, then doesn't report.|||Is the problem solved then, or you you want to elaborate on the error message ?

Jens K. Suessmeyer.

http://www.sqlserver2005.de
|||
The problem is that the runtime catches an exception. It shouldn't: it hasn't published a contract saying it will catch exceptions. It also offers very little indication that it did catch the exception.

These problems are certainly not solved.

ExecuteNonQuery hangs in Timer event notification

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);\n" +
"INSERT INTO Observation (StatisticType, StatisticObserved, StatisticValue) VALUES (2, @.When, @.AvailPageFile);\n" +
"INSERT INTO Observation (StatisticType, StatisticObserved, StatisticValue) VALUES (3, @.When, @.AvailVirtual);\n" +
"INSERT INTO Observation (StatisticType, StatisticObserved, StatisticValue) VALUES (4, @.When, @.AvailExtendedVirtual);\n");

DateTime dt = DateTime.Now;
cmd.Parameters.AddWithValue("AvailPhys", mem.ullAvailPhys);
cmd.Parameters.AddWithValue("AvailPageFile", mem.ullAvailPageFile);
cmd.Parameters.AddWithValue("AvailVirtual", mem.ullAvailVirtual);
cmd.Parameters.AddWithValue("AvailExtendedVirtual", mem.ullAvailExtendedVirtual);
cmd.Parameters.AddWithValue("When", dt);

cmd.ExecuteNonQuery();

Console.WriteLine("Inserted {0}", dt);
}

}

A-hah! It's not hanging; it's just throwing an exception that the runtime itself catches, then doesn't report.|||Is the problem solved then, or you you want to elaborate on the error message ?

Jens K. Suessmeyer.

http://www.sqlserver2005.de
|||
The problem is that the runtime catches an exception. It shouldn't: it hasn't published a contract saying it will catch exceptions. It also offers very little indication that it did catch the exception.

These problems are certainly not solved.

ExecuteNonQuery for sql2005

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:\ASPNET20\data\Northwind.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()
---

You can check SqlCommand class. You can take a look at this link:

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx

|||Search "Ole" and replace with "Sql"

ExecuteNonQuery Fails catastrophically

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?For anyone else having the same problem -
The solution is to refrain from deleting the database manually through code and also to refrain from creating the database through code. Somehow it interferes with the ExecuteNonQuery later on. From what I have made out from my research it happens mostly with Emulators. Shouldn't be an issue with real device.

ExecuteNonQuery error

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 objCmdAs SqlCommand
Private strConnAsNew 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 muybn,

there's not closing bracket for values() i mean

objCmd =New SqlCommand("INSERT INTO tblUsers (UserID,FName,LName,PrimLang1,Ctry,Phone)" & _
"VALUES('" & strUser &"','" & strFName.Text &"','" & strLName.Text &"', '" & strLang.Text &"', '" & strCtry.Text &"', '" & strPhone.Text &"')" _ 'can u see please i added a bracket )
, strConn)

regards,

satish.

|||Don't concatenate UI-supplied data to SQL statements that will be executed. This is an insecure practice as it opens up your server to SQL injection attacks. Use parameters instead.|||

Thanks, but doesn't the closing parenthesis bracket go after the reference to the connection string, in this case on the last line, strConn)?

|||

Thanks, TMorton. Is this merely a security precaution or would it cause the error I'm experiencing?

I plan to incorporate parameters into my project before I take it live. Can you point me to a definitive tutorial source for forming parameters, or better yet, mock up some of the variables that I've supplied above into parameters? To be honest, I've looked at quite a few sites and they've all confused me with how to define the parameters after the SQL statement, where you set the parameters equal to the variables.

|||

What Terri is recommending is

1) considered a best practice
2) offers protection from sql injection
3) avoids issues with getting your quotes correct when concatenating the sql. (have you considered what happens if a lastname is "O'Rourke")

Dim objCmdAs SqlCommandDim strConnAs New SqlConnection(ConfigurationManager.AppSettings("conn"))'... objCmd.Parameters.Add(New SqlParameter("@.p1", strUser)) objCmd.Parameters.Add(New SqlParameter("@.p2", strFName.Text)) objCmd.Parameters.Add(New SqlParameter("@.p3", strLName.Text)) objCmd.Parameters.Add(New SqlParameter("@.p4", strLang.Text)) objCmd.Parameters.Add(New SqlParameter("@.p5", strCtry.Text)) objCmd.Parameters.Add(New SqlParameter("@.p6", strPhone.Text)) objCmd =New SqlCommand("INSERT INTO tblUsers (UserID,FName,LName,PrimLang1,Ctry,Phone)" & _" VALUES(@.p1,@.p2,@.p3,@.p4,@.p5,@.p6)", strConn) strConn.Open() objCmd.ExecuteNonQuery()
|||

still good option is write stored procedures wherever necessary, they are better in performance as they are precompiled. rest what mike has given as example is good one.

and for earlier post values clause has its own brackets so you need to close where i mentioned earlier.

thanks,

satish

|||Thanks, now I see. Hopefully it will work now.|||

satish_nagdev:

still good option is write stored procedures wherever necessary, they are better in performance as they are precompiled.

Performance differences between dynamic sql and stored procs is one of those things that is widely disputed. Personally i'm quite fond of dynamic sql but will still use a sproc if i see a benefit. But, rather than just debate the issue, let's test it. Here I offer the results of a very simple performance test.

IterationDynSqlSproc10.0003820.00023520.0001760.00017430.0001490.00016440.0001390.00015150.0001650.00016860.0001420.00015970.0001410.00015080.0001610.00016790.0001430.000159100.0001410.000150

Since the execution plan for dynamic sql is also cached (as is the execution plan for a sproc), the dynamic sql actually turns out to be quite performant.
Note that on iteration 1, the dynamic sql suffered a little because i ran it first. If i had run the sproc first, the result would look more like this:

IterationDynSqlSproc10.0001850.00038320.0001430.00016030.0001400.00015340.0004810.00017250.0001580.00020460.0001380.00015370.0001390.00014880.0001510.00017290.0001440.000149100.0001400.000147

Both set of results were taken after running my test code a few times to try to be more consistent with how a system in motion might perform.

Of course test results mean nothing unless you know how the test was run. I ran the test on my development system where sql 2000 was also installed on the same box.

This is the test code. Please adapt it to your own real word test to see if dynamic sql can compete with your own sprocs.

The test sproc:

CREATE PROCEDURE GetUserActivity (@.userid integer)AS-- tblTransactionLog has 1 million+ rows of data-- the userid column is indexedSELECT *FROM tblTransactionLogWHERE userid = @.userId;GO

The page code:

Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.LoadDim swAs StopwatchDim drAs SqlDataReaderDim connAs SqlConnectionDim cmdDynamicAs New SqlCommandDim cmdSprocAs New SqlCommandDim dynParamAs SqlParameterDim sprocParamAs SqlParameterDim tsDynamicAs TimeSpanDim tsSprocAs TimeSpan conn =New SqlConnection("Initial Catalog=webcommon;Integrated Security=True") dynParam =New SqlParameter("@.userid", SqlDbType.Int, 4) dynParam.Value = 4347 cmdDynamic.Parameters.Add(dynParam) sprocParam =New SqlParameter("@.userid", SqlDbType.Int, 4) sprocParam.Value = 4347 cmdSproc.Parameters.Add(sprocParam) conn.Open() Using conn'prepare for sproc cmdDynamic.CommandText ="GetUserActivity" cmdDynamic.CommandType = CommandType.StoredProcedure cmdDynamic.Connection = conn'prepare for dynsql cmdSproc.CommandText ="select * from tblTransactionLog where userid = @.userid;" cmdSproc.CommandType = CommandType.Text cmdSproc.Connection = conn Response.Write("<table border=""1""><tr><th>Iteration</th><th>DynSql</th><th>Sproc</th></tr>")For indexAs Integer = 1To 10'going first incurs a small performance penalty on the very first iteration sw = Stopwatch.StartNew dr = cmdSproc.ExecuteReader() tsSproc = sw.Elapsed dr.Close() sw = Stopwatch.StartNew dr = cmdDynamic.ExecuteReader() tsDynamic = sw.Elapsed dr.Close() Response.Write(String.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>", index, tsDynamic.TotalSeconds.ToString("n6"), tsSproc.TotalSeconds.ToString("n6")))Next Response.Write("</table>")End UsingEnd Sub
|||

satish_nagdev:

still good option is write stored procedures wherever necessary, they are better in performance as they are precompiled.

This is misguided advice. There are good reasons to use stored procedures, but performance is not one of them. There are places where *not* using stored procedures is a better option. This topic (stored procedures vs. inline SQL) is the subject of a lot of heated, well-reasoned discussion in the blogosphere.

|||How awesome that you would take the time to detail all this for me! Thanks. I will test it out soon. Right now, I have to go one step at a time understanding the underlying principles and solving some other errors that are showing up.|||Mike, I'm getting this error while trying to use your suggestion on parameters: "Object reference not set to an instance of an object." This comes with each line that begins with "objCmd.Parameters." These are merely strings, as far as I can see, so I don't know why it would be asking for object instances.|||

my bad. when adapting your code i got it out of sequence...you need to create the command object before you add the parameters.

Dim objCmdAs SqlCommandDim strConnAs New SqlConnection(ConfigurationManager.AppSettings("conn")) objCmd =New SqlCommand("INSERT INTO tblUsers (UserID,FName,LName,PrimLang1,Ctry,Phone)" & _" VALUES(@.p1,@.p2,@.p3,@.p4,@.p5,@.p6)", strConn) objCmd.Parameters.Add(New SqlParameter("@.p1", strUser)) objCmd.Parameters.Add(New SqlParameter("@.p2", strFName.Text)) objCmd.Parameters.Add(New SqlParameter("@.p3", strLName.Text)) objCmd.Parameters.Add(New SqlParameter("@.p4", strLang.Text)) objCmd.Parameters.Add(New SqlParameter("@.p5", strCtry.Text)) objCmd.Parameters.Add(New SqlParameter("@.p6", strPhone.Text)) strConn.Open() objCmd.ExecuteNonQuery()
|||

Terri, Mike,

i wont argue on that. I agree with you guys upto a limit, but mike in my last project there were heaps of inline queries we found while re-writing the application, so using procedures added positively to scalability. so depends on from situation to situation.

mike you've done testing thats good, if you get time could you do it for simultaneous instances say 10 at a go?

thanks,

satish.

|||

Inline queries should by managed in a DAL Component. My DAL is a seperate project which keeps things nice and tidy.
I actually have very few hand typed dynamic sql statements. My dynamic sql is about 99% generated on the fly.

Anyways, I put my test page through an ACT test script and here are the results. I used only 8 simultaneous connections to avoid a resultset with http errors .

Test 1 - sproc performance:

commented out the dynamic reader code inside the loop
test duration: 1 minute
Avg Requests per second: 587
Total requests completed: 35,232

Test 2 - dynamic sql performance:

commented out the sproc reader code inside the loop
test duration: 1 minute
Avg Requests per second: 601
Total requests completed: 36,082

My test setup is a little flawed since my test script was running on the same system that was under test. But, since we're just doing a head to head comparison and since both tests were subject to the same testing flaw, i'd have to conclude that dynamic sql (in this specific test case) outperformed a stored proc.

ExecuteNonQuery crash my application

I'm working on an application with Compact Framework 2 and SQL Server Mobile
2005. When the application start, if there is no data base in its folder, one
is created using CreateDataBase from SqlCeEngine (I'm sure that every object
used for that operation is closed after create the file). After that, it
pulls the data from a SQL Server 2000.
In Windows Mobile 2005, everything works fine... but when my application is
running under Windows CE 4.2, after any synchronization, if I throw any
instruction like "UPDATE" or "INSERT" (not with "DELETE") with
ExecuteNonQuery, the application crashes and exits without an error
notification. When I try to open the application without synchronization
because it's unnecessary, everything works fine. If I try to make another
synchronization, works... but then I throw another instruction with
ExecuteNonQuery, it crashes the same way.
So, my solution was to close the application everytime there is a
synchronization, but that's useless.
I've tried not to create the database with code, dropping all the tables
before the synchronization and it works... but it crashes anyway when I use
ExecuteNonQuery.
?Is there any solution for this? ?Anyone has the same problem?
I too have an application developed in .NET CF 2.0 , with SQL CE 3.0
database. I am executing the application on HP-iPAQ Win CE 4.2 device. When
there is a call to
update, and ExecuteNonQuery, the application crashes.
Synchronization is done with ADO.Net. Is there a way to resolve this?
Thanks,
Sangeetha

ExecuteNonQuery - Add working/Update not working

I am writing a pgm that attaches to a SQL Server database. I have an Add stored procedure and an Update stored procedure. The two are almost identical, except for a couple parameters. However, the Add function works and the Update does not. Can anyone see why? I can't seem to find what the problem is...

This was my test:


Dim cmd As New SqlCommand("pContact_Update", cn)
'Dim cmd As New SqlCommand("pContact_Add", cn)

Try
cmd.CommandType = CommandType.StoredProcedure

cmd.Parameters.Add("@.UserId", SqlDbType.VarChar).Value = UserId
cmd.Parameters.Add("@.FirstName", SqlDbType.VarChar).Value = TextBox1.Text
[...etc more parameters...]
cmd.Parameters.Add("@.Id", SqlDbType.VarChar).Value = ContactId

cn.Open()
cmd.ExecuteNonQuery()

Label1.Text = "done"
cn.Close()

Catch ex As Exception
Label1.Text = ex.Message
End Try

When I use the Add procedure, a record is added correctly and I receive the "done" message. When I use the Update procedure, the record is not updated, but I still receive the "done" message.

I have looked at the stored procedures and the syntax is correct according to SQL Server.

Please I would appreciate any advice...Before you do your executeNonQuery - - make sure (do a response.write or a Trace.Write) to make sure your USERID and textbox1.text values are actually populated.

Many times, if the update statement has a where clause, and it continues through, the WHERE arguments are not being fulfilled.|||Thanks for your reply...
I followed the code and the Id field is getting a value. I also added:


Dim NbrRows As Integer = cmd.ExecuteNonQuery()
Label1.Text = NbrRows

And I do receive a message that 1 row has been affected. However, the value I entered changes back to the original value and the record is not updated.