如何在单独的表中使用reader.GetDecimal()?

时间:2013-07-16 14:59:03

标签: c# desktop-application sqlcommand

我的数据库中有两个表:学生和帐户。在我的应用程序中,我正在尝试使用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);

3 个答案:

答案 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");

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

http://msdn.microsoft.com/en-us/library/system.data.datatablereader.getdecimal(v=vs.90).aspx

您可以使用此

decimal total = reader.GetDecimal(2); //index column name

希望能帮到你