In C# ADO.NET, how can I tell if a sproc returned 0 rows versus the sproc had no commands to run on TSQL?
Let me lay it out in full. In TSQL I have (when I open this in SSMS)
ALTER PROC mySproc
@myvar VARCHAR(10)
AS
/* commente开发者_Go百科d out on dev system - uncomment on production */
/* guess what didn't happen */
/* careful readers will note that we _normally_
throw an exception when we do this. this sproc was missing said exception. */
When run in SSMS mySproc 'value'
this says "Command(s) completed successfully." Under better circumstances (aka just no data returned but the body of the sproc is actually running), it would return what looked like a table but with no rows.
and in C#:
using( SqlDataReader reader = cmd.ExecuteReader() ){
//reader.HasRows == false
}
So, that's what I ran into, and without using "sql reflection" (ergo reading the actual script in the database) and without using an ORM (because then I would know that I was sending the right commands, but we have our reasons for using sprocs, of course) ...
How can I tell that I got a result of "Command(s) completed successfully." instead of a potential table with just no rows?
I originally put this in a comment but it is more appropriate as an answer
You can use the FieldCount
property on the reader to determine the number of columns. For example:
using( SqlDataReader reader = cmd.ExecuteReader() )
{
if (reader.FieldCount > 0)
{
// there are columns
}
else
{
// there are no columns, so stored proc returning no results set
}
}
From the MSDN page on FieldCount
Executing a query that, by its nature, does not return rows (such as a DELETE query), sets FieldCount to 0. However. this should not be confused with a query that returns 0 rows (such as SELECT * FROM table WHERE 1 = 2) in which case FieldCount returns the number of columns in the table, including hidden fields. Use VisibleFieldCount to exclude hidden fields.
I would suggest auditing SQL Server and beating the crap out of developers that actually create SPROCs without bodies. I know of no way to determine stupidity in SQL Server from a reader other than actually issuing an audit when there are no rows (running something like sp_helptext and determine if there is a body?). It is hard to protect from sloppiness. Sorry!
精彩评论