Sunday, February 19, 2012

Checking for Row Existence

Can someone show me some C# code for detecting if a SQL row exists or not? This seems like a very typical action and I cannot for the life of me find a tutorial online that explains this step. In my code I'm either going to INSERT or UPDATE a record. I tried sending a SELECT command through a ExecuteNonQuery, but only got -1 as a response. Apparently ExecuteNonQuery does not work with SELECT. I then saw that T-SQL has an EXISTS keyword, but I cannot see anyway to use that from within C#.

So...can anyone share the typical code they use to identify if a row exists or not within a database. I guess I was execting there to be some method available to do this sort of thing.

There are two methods i use

Method A)

Which uses the Execute Scalar to return the results of a SQL COUNT

i.e.

 cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();

Here is a nice example i found for you

http://www.java2s.com/Code/CSharp/Database-ADO.net/GetrowcountbyExecuteScalar.htm

Method B)

Using a datareader and has.rows

Add ; to make it c# as you see fitStick out tongue

Dim objTransport As SqlDataReader
objTransport = myCommand.ExecuteReader(CommandBehavior.CloseConnection)

If objTransport.HasRows Then
Return ("True")
Else
Return ("False")
End If
myConnection.Close()

Method A is more efficient as your only passing around a very small number between the webserver and database.

Hope that helpsSmile

No comments:

Post a Comment