在 C# ADO.NET 中,如何判断存储过程是否返回 0 行,以及存储过程是否没有在 TSQL 上运行的命令?
在 C# ADO.NET 中,如何判断存储过程是否返回 0 行,以及存储过程是否没有在 TSQL 上运行的命令?
让我完整地阐述一下。在 TSQL 中,我(当我在 SSMS 中打开它时)
ALTER PROC mySproc
@myvar VARCHAR(10)
AS
/* commented 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. */
在 SSMS mySproc 'value'
中运行时,显示“命令成功完成”。在更好的情况下(也就是没有返回数据,但存储过程的主体实际上正在运行),它将返回看起来像表但没有行的内容。
在 C# 中:
using( SqlDataReader reader = cmd.ExecuteReader() ){
//reader.HasRows == false
}
所以,这就是我遇到的情况,并且没有使用“sql 反射”(因此读取数据库中的实际脚本),也没有使用 ORM(因为这样我就知道我发送了正确的命令,但我们当然,我们有使用存储过程的原因)...
我如何知道我得到了“命令成功完成”的结果。而不是一个没有行的潜在表?
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
/* commented 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我最初将其放在评论中,但作为答案更合适
您可以使用阅读器上的
FieldCount
属性来确定列数。例如:来自 MSDN 页面在
FieldCount
上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:From the MSDN page on
FieldCount
我建议审计 SQL Server 并击败那些实际上创建没有主体的 SPROC 的开发人员。我知道除了在没有行时实际发出审核(运行 sp_helptext 之类的东西并确定是否有主体?)之外,没有其他方法可以从读者那里确定 SQL Server 中的愚蠢行为。很难防止马虎。对不起!
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!