使用存储过程从数据库获取值?

时间:2014-05-05 21:36:48

标签: c# sql sql-server stored-procedures linq-to-sql

我有一个存储过程来获取UserId的最后一行值:

ALTER PROCEDURE [dbo].[get_LoginStatusQ]  
    @UserId int
AS   
BEGIN  
   SELECT MAX(UserTimeId), LoginStatus 
   FROM UserTime 
   WHERE UserId = @UserId 
   GROUP BY UserId, LoginStatus, Day, HoursWorked, Date, CheckIn,UserTimeId 
END

在C#中,我想获取LoginStatus的值。怎么做我这样做?

我试过了:

public void GetLogin(object sender, EventArgs e)
{ 
   db.get_LoginStatusQ(Convert.ToInt32(Session["userid"])));

   if( LoginStatus ='In') // How do I get the field LoginStatus from the database?
   {
   }
}

2 个答案:

答案 0 :(得分:0)

您的存储过程需要一些修复,请参阅下文:

ALTER PROCEDURE [dbo].[get_LoginStatusQ]  
@UserId int
AS   
BEGIN  
 SET NOCOUNT ON;

    SELECT TOP 1 UserTimeId, LoginStatus 
    FROM UserTime 
    WHERE UserId = @UserId 
    ORDER BY UserTimeId DESC
END

答案 1 :(得分:0)

为您的C#代码尝试这样的事情,确保在您使用时有以下内容 如果您没有自己设置的DAL类,可以将Method签名的声明更改为Private。

using System.Data;
using System.Data.SqlClient;

    public static DataSet GetLogin(Int32 userId)
    {
       DataSet logStatusDs = new DataSet();
        //load the List one time to be used thru out the intire application
        var ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["CMSConnectionString"].ConnectionString;
        using (SqlConnection connStr = new SqlConnection(ConnString))
        {
            using (SqlCommand cmd = new SqlCommand("get_LoginStatusQ", connStr))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@UserId", userId);
                cmd.Connection.Open();
                new SqlDataAdapter(cmd).Fill(logStatusDs);
            }
        }
        return logStatusDs;
    }