2011-11-18 3 views
0

테이블의 행 수를 반환하는 SQL 쿼리를 실행할 수 있는지 알고 싶습니다. 클릭 한 페이지에서 두 테이블 사이의 데이터를 비교하는 SQL 쿼리를 실행하므로 하나 이상의 테이블이 비어 있으면 사용자에게 알릴 수 있습니다.SQL Store 테이블의 행 수

SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"); 

    SqlCommand nonqueryCommand = thisConnection.CreateCommand(); 

    try 
    { 
     thisConnection.Open(); 
     //sql statement to check if a table is empty 
     //stores the count value in a integer X 

     if(X < 1) 
     { 
     Response.Write("<script>alert('Database X is empty');</script>"); 
      return; 
     } 
    } 

품질 평가 점수는 : 나는 테이블의 행 수를 검색 할 Select Count(*) from Table를 사용하십니까?

어떻게 Count (*) 값을 Integer에 저장합니까?

미리 감사드립니다.


SQL Server를 사용하고 있습니다.

+0

대신 수를 확인, 당신은 테이블이어야 경우를 확인 할 수 TOP 1을 사용하여 1 행. 그렇지 않니? – shahkalpesh

+0

TOP 1은 매우 특정한 서버입니다. Oracle, DB2, MySql에서는 작동하지 않습니다. OP는 DB 벤더에 대해 아직 언급하지 않았다. –

+0

안녕하세요 shahkalpesh, 성명을 추측 SELECT TOP 1 * FROM 테이블 것입니다. 하지만 나중에 빈 또는 null이 아닌지 확인하는 방법은 무엇입니까? – gymcode

답변

2

시도 뭔가 :

public int CountRowsInTable() 
{ 
    string stmt = "SELECT COUNT(*) FROM dbo.YourTable"; 
    int count = 0; 

    using(SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE")) 
    using(SqlCommand cmdCount = new SqlCommand(stmt, thisConnection)) 
    { 
     thisConnection.Open(); 
     count = (int)cmdCount.ExecuteScalar(); 
     thisConnection.Close(); 
    } 

    return count; 
} 

다시이 작동하고 당신에게 정확한 카운트를 제공합니다 -하지만 큰 테이블에 매우 매우 느릴 수 있습니다.

대안 : 대략 수 (정확하지 -하지만 빠른) 얻을 수있는 시스템 카탈로그 뷰에

  • 들여다
  • 가 포함되지 않습니다 -하지만 단지 당신이 적어도 하나 개의 행이 있는지 확인을 에 단순히 체 :

업데이트 (SELECT TOP 1....를 사용하고 당신은 뭔가 등을 얻을 수 있는지 확인) CK 테이블이에서 모든 행을 포함되어 있는지 여부, 당신은 정말 빨리해야이 TOP 1 접근 사용할 수 있습니다 - 심지어 대형 테이블을 :

public bool TableContainsAnyRows() 
{ 
    // define a TOP 1 query - typically by the Primary Key of the table in question 
    // using AdventureWorks sample database here 
    string stmt = "SELECT TOP 1 [BusinessEntityID] FROM Person.Person ORDER BY [BusinessEntityID]"; 

    bool containsAnyRows = false; 

    // open a connection and execute this query against the database 
    using(SqlConnection _con = new SqlConnection("server=.;database=AdventureWorks2008R2;integrated Security=SSPI;")) 
    using(SqlCommand _cmd = new SqlCommand(stmt, _con)) 
    { 
     _con.Open(); 

     // getting the result of the query 
     // if the table contains *any* rows, the result will *NOT* be NULL 
     object result = _cmd.ExecuteScalar(); 
     _con.Close(); 

     containsAnyRows = (result != null); 
    } 

    return containsAnyRows; 
} 
+0

변수에'TOP 1 '을 사용하여 쿼리를 저장하고 null이 아닌지 확인하려면 어떻게해야합니까? – gymcode

+0

@RUiHAO : 내 응답을 'TOP 1'검색어의 예로 업데이트했습니다. –

0
SELECT COUNT(*) FROM yourtable; 

결과에서 첫 번째 행을 검색하십시오. 이 같은

+0

어떻게 카운트 값을 정수로 저장합니까? – gymcode

+0

이것은 프로그래밍 언어에 따라 다릅니다. 나는 당신이 자바를 사용하지 않고있는 것을 볼 수 있으며 나는 추측하고 싶지 않다. –

+0

C# 언어를 사용하고 있습니다. – gymcode