2016-07-30 2 views
-2

C#에서 선택 쿼리를 실행하면 얼마나 많은 행이 영향을 받는지 확인하고 싶습니다. 데이터 세트 또는 데이터 테이블에 데이터를 삽입하지 않아도됩니다.C에서 선택 쿼리에 의해 영향을받은 행 수를 찾는 방법 #

는 현재 쿼리 사용 ExecuteReader()에 대한 모든의 아래 말 루프를 읽는 동안
string constr = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString; //get connection string Web.config 

SqlConnection con = new SqlConnection(constr); 

//define Select Query 
SqlCommand slct = new SqlCommand("select * From [dbo].[userdetail] where 1=1", con); 
int noRows; 

//open connection and execute query 
con.Open(); 
noRows = slct.ExecuteNonQuery(); 
con.Close(); 

//define Select Query 
SqlCommand select = new SqlCommand("select * From [dbo].[userdetail] where 1=0", con); 

//open connection and execute query 
con.Open(); 
noRows = select.ExecuteNonQuery(); 
con.Close(); 
+1

그런 경우'SELECT COUNT (*) .....'를 사용하고'select.ExecuteScalar()'를 사용하여 행 수를 되 찾을 필요가있다 –

+0

데이터베이스에서 검색된 데이터 집합의 행 수를 계산할 수 있습니다 – Jonny

+0

"영향을받는 대상"을 정의해야합니다. 왜냐하면 당신이 "선택"을 의미했다면 그것은 위에서 언급 한 것과 같은 결과를 세는 것을 의미하기 때문입니다. – KernelMode

답변

0

먼저

int count = 0; 

while(rdr.Read()) 
{ 
    count++; 
} 
그렇지

은, 아래와 같이 스칼라 쿼리를 사용하고 사용 카운터를 유지 ExecuteScalar() 기능

select count(*) From [dbo].[userdetail] 

SqlCommand cmd = new SqlCommand("select count(*) From [dbo].[userdetail]", con); 

// open connection and execute query 
con.Open(); 
int noRows = (int)cmd.ExecuteScalar(); 
관련 문제