executenonquery returning -1 problem

M

Manikandan

Hi,
I'm using executenonquery to check the existence of table in the
database.
I tried two methods of queries, everything return -1 even though table
exists in database

Code as below
SqlConnection connection=new SqlConnection("Data Source=\LOCAL;
Initial Catalog=ff; Integrated Security=SSPI; Persist Security
Info=False; ");
connection.Open();
string tableExistsCheckQuery="SELECT * FROM
INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='resultsc'";
//string tableExistsCheckQuery="SELECT * FROM dbo.sysobjects WHERE
id =OBJECT_ID(N'[dbo].[resultsc]')AND OBJECTPROPERTY(id,
N'IsUserTable') = 1";

SqlCommand command=new
SqlCommand(tableExistsCheckQuery,connection);
int a=command.ExecuteNonQuery();
'a' always return -1 if table exists in data base or not
I tried changing the query as below
string tableExistsCheckQuery="SELECT * FROM dbo.sysobjects WHERE id
=OBJECT_ID(N'[dbo].[resultsc]')AND OBJECTPROPERTY(id, N'IsUserTable')
= 1";

its also returning -1.

Is there any mistake in my code?

Thanks,
Mani
 
J

Jon Skeet [C# MVP]

I'm using executenonquery to check the existence of table in the
database.
I tried two methods of queries, everything return -1 even though table
exists in database

Is there any mistake in my code?

Yes - you're using a select statement and expecting a result other
than -1. From the docs:

<quote>
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.
</quote>

Now, are you trying to get the count from your query, if so,
ExecuteScalar is probably what you're after.

Jon
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

A better approach would be:

SELECT count(*) FROM ......

and in your code:

bool exist = Convert.ToBoolean( com.ExecuteScalar() );
 
M

Michael Letterle

Hi,

A better approach would be:

SELECT count(*) FROM ......

and in your code:

bool exist = Convert.ToBoolean( com.ExecuteScalar() );

or even just Select 1 from...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top