C# 如何使用 SqlDataReader 读取行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11689875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read rows count using SqlDataReader
提问by fdgfdgs dfg
I came across a stored procedure that is returning number of rows but am not sure how can I read number of rows here,
我遇到了一个返回行数的存储过程,但我不确定如何在这里读取行数,
Stored procedure is:
存储过程是:
CREATE PROCEDURE [dbo].[Document_Exists]
(
@Url varchar(255)
)
AS
SET NOCOUNT ON;
SELECT COUNT(*) AS Rows
FROM Document_Instances
WHERE Url = @Url
Executed as
执行为
EXEC @return_value = [dbo].[Document_Exists]
@SourceSiteUrl = N'https://cc23.dev.com/portal'
SELECT 'Return Value' = @return_value
trying to read it with this code
尝试使用此代码阅读它
SqlCommand cmd1 = new SqlCommand("Document_Exists", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add(new SqlParameter("@Url", url));
SqlDataReader rdr1 = cmd.ExecuteReader();
while (rdr1.Read())
{
dunno what to do next
不知道接下来要做什么
采纳答案by juergen d
try
尝试
int rows = 0;
if(rdr1.Read()) {
rows = (int) rdr1["Rows"];
}
回答by Shyju
int totalRows=0;
if(rdr1.Read())
{
totalRows= rdr1.GetInt32(rdr1.GetOrdinal("Rows"));
}
If you are retuning only a single value, I recommend you to use ExecuteScalar
如果您只重新调整一个值,我建议您使用 ExecuteScalar
回答by Steve
Where is the point to use SqlDataReader when you return a single value from your proc?
当您从 proc 返回单个值时,使用 SqlDataReader 的重点在哪里?
SqlCommand cmd1 = new SqlCommand("Document_Exists", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add(new SqlParameter("@Url", url));
int rows = Convert.ToInt32(cmd.ExecuteScalar());
回答by GHMS
int rowCount = dataReader.Cast<object>().Count();

