2011-06-11 5 views
2

asp.net에 user.sdf 데이터베이스가 있습니다. 테이블을 만들고 싶습니다. 먼저 확인하십시오. 먼저 존재하는지 확인하십시오. 테이블, 그렇지 않으면 새 테이블을 만들 수 있습니다.이 문제를 해결하는 데 도움이되도록 어떻게 확인할 수 있습니까?테이블이 SQL Server CE 3.5에 있는지 여부를 확인할 수 있습니다.

+3

당신은 무엇을 시도 했습니까 - 어떤 문서를보고 몇 가지 예를 들어 보셨습니까? 현재 작동 중이거나 질문이있는 코드를 게시하십시오. See [ask] – Hogan

답변

9

SQL CE 3.5의 스키마 뷰는 here으로 쿼리 할 수 ​​있습니다.

다음은 사용할 수있는 간단한 확장 방법입니다. 당신이 테이블을 쿼리 던져 예외를 잡을 수있는 대안으로

using (SqlCeConnection connection = new SqlCeConnection(@"Data Source=MyDatabase1.sdf")) 
{ 
    connection.Open(); 
    if (connection.TableExists("MyTable")) 
    { 
    // The table exists 
    } 
    else 
    { 
    // The table does not exist 
    } 
} 
0

을 다음과 같이

public static class SqlCeExtentions 
{ 
    public static bool TableExists(this SqlCeConnection connection, string tableName) 
    { 
    if (tableName == null) throw new ArgumentNullException("tableName"); 
    if (string.IsNullOrWhiteSpace(tableName)) throw new ArgumentException("Invalid table name"); 
    if (connection == null) throw new ArgumentNullException("connection"); 
    if (connection.State != ConnectionState.Open) 
    { 
     throw new InvalidOperationException("TableExists requires an open and available Connection. The connection's current state is " + connection.State); 
    } 

    using (SqlCeCommand command = connection.CreateCommand()) 
    { 
     command.CommandType = CommandType.Text; 
     command.CommandText = "SELECT 1 FROM Information_Schema.Tables WHERE TABLE_NAME = @tableName"; 
     command.Parameters.AddWithValue("tableName", tableName); 
     object result = command.ExecuteScalar(); 
     return result != null; 
    } 
    } 
} 

당신은 위의를 사용할 수 있습니다. 예외가있는 경우 테이블을 찾을 수 없거나 테이블이 존재합니다.

SELECT TOP 1 1 FROM TableName; 

간단하고 간단한 성능 테스트는 INFORMATION_SCHEMA에 대한 쿼리보다 나은 결과입니다. 내가 INFORMATION_SCHEMA에 대한 쿼리를 더 깔끔하다고 생각할지라도.

관련 문제