2010-11-26 9 views
1

Ich habe eine Funktion, wie dies für die Bindung des Primärschlüssels aus der ausgewählten Datenbank in einem ComboBox gibt:Warum die Funktion unerwünschter Wert

//An instance of the connection string is created to manage the contents of the connection string. 

var sqlConnection = new SqlConnectionStringBuilder(); 
sqlConnection.DataSource = "192.168.10.3"; 
sqlConnection.UserID = "gp"; 
sqlConnection.Password = "gp"; 
sqlConnection.InitialCatalog = Convert.ToString(cmbDatabases.SelectedValue); 
string connectionString = sqlConnection.ConnectionString; 

SqlConnection sConnection = new SqlConnection(connectionString); 

//To Open the connection. 
sConnection.Open(); 

//Query to select the table_names that have PRIMARY_KEYS. 
string selectPrimaryKeys = @"SELECT TABLE_NAME 
          FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
          WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
          ORDER BY TABLE_NAME"; 

//Create the command object 
SqlCommand sCommand = new SqlCommand(selectPrimaryKeys, sConnection); 

try 
{ 
    //Create the dataset 
    DataSet dsListOfPrimaryKeys = new DataSet("INFORMATION_SCHEMA.TABLE_CONSTRAINTS"); 

    //Create the dataadapter object 
    SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeys, sConnection); 

    //Provides the master mapping between the sourcr table and system.data.datatable 
    sDataAdapter.TableMappings.Add("Table", "INFORMATION_SCHEMA.TABLE_CONSTRAINTS"); 

    //Fill the dataset 
    sDataAdapter.Fill(dsListOfPrimaryKeys); 

    //Bind the result combobox with primary key tables 
    DataViewManager dvmListOfPrimaryKeys = dsListOfPrimaryKeys.DefaultViewManager; 
    cmbResults.DataSource = dsListOfPrimaryKeys.Tables["INFORMATION_SCHEMA.TABLE_CONSTRAINTS"]; 
    cmbResults.DisplayMember = "TABLE_NAME"; 
    cmbResults.ValueMember = "TABLE_NAME"; 
} 
catch(Exception ex) 
{ 
    //All the exceptions are handled and written in the EventLog. 
    EventLog log = new EventLog("Application"); 
    log.Source = "MFDBAnalyser"; 
    log.WriteEntry(ex.Message); 
} 
finally 
{ 
    //If connection is not closed then close the connection 
    if(sConnection.State != ConnectionState.Closed) 
    { 
     sConnection.Close(); 
} 

Aber es ist was ein unerwünschtes Ergebnis wie dtproperties.Is etwas falsch mit der Abfrage.

+3

Was ist die erwartete Ausgabe und was ist der Stromausgang? Wir brauchen mehr Details. Haben Sie versucht, die Abfrage direkt mit der Datenbank auszuführen, indem Sie etwas wie SQL Management Studio verwenden? – TheCloudlessSky

+0

ja in der Abfrage gibt es ein Problem .... Es zeigt das gleiche Ergebnis in SQL Management Studio. – Srivastava

+0

hey, deine 'SqlConnection' ist nicht am Ende der Methode angeordnet! –

Antwort

1

dtproperties ist eine Tabelle von SQL Server verwendet Diagramminformationen zu speichern. In einigen Versionen von SQL Server ist es als Benutzertabelle (und nicht als Systemtabelle) gekennzeichnet und wird daher von Abfragen zurückgegeben, die nach Benutzertabelle suchen.

Vielleicht ist es nur herausfiltern mit so etwas wie:

string selectPrimaryKeys = @"SELECT 
             TABLE_NAME 
            FROM 
             INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
            WHERE 
             CONSTRAINT_TYPE = 'PRIMARY KEY' 
             AND TABLE_NAME <> 'dtproperties' 
           ORDER BY 
             TABLE_NAME"; 
0

Obwohl Primärschlüssel technisch Teil von Tabellen und nicht von Datenbanken sind, sollten Sie, wenn Ihre Abfrage korrekt ist, dies für Ihren C# -Code versuchen. Es hat ein paar Speicher- und Leistungsverbesserungen, sowie Verbindungsunterbrechungen.

public void GetPrimaryKeyTable() { 
    //An instance of the connection string is created to manage the contents of the connection string. 

    var sqlConnection = new SqlConnectionStringBuilder(); 
    sqlConnection.DataSource = "192.168.10.3"; 
    sqlConnection.UserID = "gp"; 
    sqlConnection.Password = "gp"; 
    sqlConnection.InitialCatalog = Convert.ToString(cmbDatabases.SelectedValue); 

    // Automatically close the connection 
    using(SqlConnection sConnection = new SqlConnection(sqlConnection.ConnectionString)) { 
     try { 
      sConnection.Open(); 

      //Query to select the table_names that have PRIMARY_KEYS. 
      string selectPrimaryKeys = @"SELECT TABLE_NAME 
             FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
             WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
             ORDER BY TABLE_NAME"; 

      //Create the command object 
      using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeys, sConnection)) { 
       // Bind the combobox without destroying the data reader object after binding (no using statement) 
       cmbResults.DisplayMember = "TABLE_NAME"; 
       cmbResults.ValueMember = "TABLE_NAME"; 
       cmbResults.DataSource sReader = sCommand.ExecuteReader(); 
       cmbResults.DataBind(); 
      } 
     } 
     catch(Exception ex) { 
      // All the exceptions are handled and written in the EventLog. 
      EventLog log = new EventLog("Application"); 
      log.Source = "MFDBAnalyser"; 
      log.WriteEntry(ex.Message); 
     } 
     finally { 
      // Read somewhere that the using statement takes care of this for you 
      // but just in case 
      if(sConnection.State != ConnectionState.Closed) { 
       sConnection.Close(); 
      } 
     } 
    } 
} 

Wie für Ihre Abfrage in SQL Server 2008 R2, gibt es eine Liste der Tabellen, die Primärschlüssel haben (jede Tabelle in der Liste ist eine Tabelle mit einem Primärschlüssel). Welche Version von SQL Server verwenden Sie?

EDIT: Wenn Sie Ihre Abfrage auf Rückkehr USER Tabellen wollen und Dinge wie Systemtabellen herauszufiltern, versuchen Sie diese Abfrage:

SELECT tc.TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc 
INNER JOIN sysobjects so 
     ON tc.TABLE_NAME = so.name 
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' 
     AND so.xtype = 'U' 
ORDER BY TABLE_NAME; 
+1

Verwenden Sie 'using' Block – abatishchev

+0

Es zeigt Fehler in ExecuteDataReader(); – Srivastava

+0

Mein Fehler, der Methodenname ist ExecuteReader() not ExecuteDataReader(). Ich habe meine Antwort aktualisiert, um dies zu berücksichtigen. – bitxwise

Verwandte Themen