2013-07-16 21 views
0

我在我的数据库中有两个表格:学生和帐户。在我的应用程序中,我尝试使用reader.GetDecimal()方法从多个表中读取数据,并且无法从第二个表中获取数据。如何将reader.GetDecimal()用于单独表中的列?

使用GetDecimal方法可以做到这一点吗?或者,我是否需要添加其中一个查询以获得我需要的帐户表?

数据库表:

账户

Accounts

学生 Student

代码:

  //Query Student table for bAlertSetup 
      SqlCeCommand AlertQuery = new SqlCeCommand("SELECT * from Students AND Accounts", conn); 
      reader = AlertQuery.ExecuteReader(); 

      while (reader.Read()) 
      { 
       bSinglePersonAlertSetup = reader.GetBoolean(5); 

       if (bSinglePersonAlertSetup == true) 
       { 
        int AccountID = reader.GetInt32(7); 
        decimal Threshold = reader.GetDecimal(6); 
        //decimal Total = get decimal from the accounts table where accountID (in the accounts table) = AlertAccountID 

        //See if Students account is below the defined threshold 
        if (Total < Threshold) 
        { 
         StudentEmailAddress = reader.GetString(3); 

         if (StudentEmailAddress != null) 
         { 
          Console.WriteLine(StudentEmailAddress); 
          mail.To.Add(StudentEmailAddress); 

          //Update bAlertSetup 
          SqlCeCommand UpdateBool = new SqlCeCommand("UPDATE Students set bSendAlert = 0 WHERE UserId = @ID"); 
          UpdateBool.Parameters.AddWithValue("@ID", reader.GetInt32(0)); 
          UpdateBool.Connection = conn; 
          UpdateBool.ExecuteNonQuery(); 
         } 
        }  
       } 

编辑:

这里是我使用,我相信,需要对列进行正确连接两个表的新查询。现在,我如何获得GetDecimal()方法中使用的每列的索引?

SqlCeCommand AlertQuery = new SqlCeCommand("SELECT st.bAlertSetup, st.AccountThreshold, st.AlertAccountID, acc.AccountID, acc.AccountTotal FROM Students st INNER JOIN Accounts acc ON st.AlertAccountID = acc.AccountID", conn); 
+0

试试这个:read.GetDecimal(6)的ToString()。 – Marek

+0

您需要在此处编辑您的查询以获取第二个表中的列。 – Ehsan

+0

我相信这部分目前的工作原理是如何的。我遇到的问题是从帐户表中获取相应的“AccountID”和“AccountTotal”。 –

回答

1
SqlCeCommand AlertQuery = new SqlCeCommand("SELECT S.*,A.AccountTotal from Students S Inner Join Accounts A ON S.AlertAccountID = A.AccountID"); 

确保在SQL中执行查询并且知道每列的索引以提供正确的索引,或用S. 替换[FieldName],以便分隔每个字段逗号,并且列的顺序将始终保留在查询中。

+0

如果我在查询中定义了每个列,例如S.AccountThreshold,S.AlertAccountID。我用于GetDeimal()方法的索引是否与我在查询中列出的顺序相对应?所以我会使用GetDecimal(0)来查找AccountThreshold? –

+1

的确如此,如果S.AccountThreshold在您的查询中首先出现,那么它在索引0 –

+0

它完美地工作。非常感谢你! –

1

你应该适当加入查询两个表,并且只选择您需要的各列。所以,您的查询可能类似于下面...

SELECT st.UserID, st.FirstName, st.LastName, acc.AccountName, acc.AccountTotal 
FROM Student st 
JOIN Accounts acc 
ON st.AlertAccountID = acc.AccountID 

你可以得到AccountTotal然后通过名字,像这样...

decimal total = reader.GetDecimal("AccountTotal"); 
+0

编译时出现无法将字符串转换为int错误的情况。有没有办法从列名中获取表中的索引? –

相关问题