从SQL查询返回多个变量

时间:2013-08-15 13:49:27

标签: c# sql database tsql variables

我的表格结构如下:

Session
--------------
SessionID (PK)
RoomID     
SessionDate
SessionTimeStart
SessionTimeEnd

我有一个以下查询,它将始终返回一行并显示在DGV中。我使用DataAdapter进行连接:

        DataTable queryResult = new DataTable();
        string ConnStr = "Data Source=DUZY;Initial Catalog=AutoRegSQL;Integrated Security=True";

        SqlConnection MyConn = new SqlConnection(ConnStr);
        MyConn.Open();

        //SQL query that returns todays sessions for the given roomID
        string query = @"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
           " FROM [Session] " +
           " WHERE RoomID = @RoomID " +
           " AND SessionDate = cast(getdate() as date) ";

        SqlCommand command = new SqlCommand(query, MyConn);

        command.Parameters.Add("RoomID", SqlDbType.Char).Value = RoomID;


        SqlDataAdapter adapter = new SqlDataAdapter(command);

        adapter.Fill(queryResult);

我想将查询结果保存到表示表列的多个字符串中,即

SessionIDstring = query result for SessionID column
RoomIDstring = query result for RoomID column
and so on...

是否可以使用一个查询来实现它,或者我是否必须为每列创建5个查询?

3 个答案:

答案 0 :(得分:2)

使用ADO.NET可能与此类似吗?

    //SQL query that returns todays sessions for the given roomID
string query = @"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
                " FROM [Session] " +
                " WHERE RoomID = @RoomID " +
                " AND SessionDate = cast(getdate() as date) ";

using (var connection = new SqlConnection(ConnStr))
using (var command = new SqlCommand(query, connection))
{
    command.Parameters.Add("RoomID", SqlDbType.Char).Value = RoomID;

    try
    {
        connection.Open();

        using (SqlDataReader reader = command.ExecuteReader())
        {
            if (reader.Read())
            {
                // Note that reader[x] has the equivalent type to the type
                // of the returned column, converted using
                // http://msdn.microsoft.com/en-us/library/cc716729.aspx
                // .ToString() if the item isn't null is always ok
                string SessionIDstring = reader[0].ToString(); // it should be an int

                // reading it twice is ok
                int RoomID = (int)reader[1]; // it should be an int
                string RoomIDstring = reader[1].ToString(); // it should be an int

                if (reader.Read())
                {
                    throw new Exception("Too many rows");
                }
            }
            else 
            {
                throw new Exception("No rows");
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

此代码改编自MSDN ADO.NET Code Examples。我添加了一些using并将其设为单行。我甚至不想知道为什么MSDN示例不能与using完全一致。

请注意,构建SqlDataAdapter是为了恢复多行/大数据并将它们放在DataSet中。您可以将它们用于单行数据,但如果您只想填充某些变量,则只需使用SqlDataReader就容易得多。

答案 1 :(得分:1)

declare @col1 int
declare @col2 varchar(42)

select  @col1 = col1
,       @col2 = col2
,       ....

答案 2 :(得分:1)

你可以像这样创建一个类......

public class SessionDto
{
    public string SessionID {get; set;}  
    public string RoomID {get; set;}     
    public string SessionDate {get; set;} 
    public string SessionTimeStart {get; set;} 
    public string SessionTimeEnd {get; set;} 
}

然后有一个获取房间ID并构建会话对象的方法

public SessionDto GetSessionData(int roomId)
{
    using (var cnn = new SqlConnection(ConnStr))
    {
        SessionDto sessionDto;

        string query = @"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
       " FROM [Session] " +
       " WHERE RoomID = @RoomID " +
       " AND SessionDate = cast(getdate() as date) ";


        cnn.Open();
        using (var cmd = new SqlCommand(query,cnn))
        {
            cmd.Parameters.Add("@RoomID", SqlDbType.Char).Value = roomId;

            using (var rdr = cmd.ExecuteReader())
            {
                if (rdr.HasRows)
                {
                    while (rdr.Read())
                    {
                        sessionDto = new sessionDto{
                            SessionID = rdr.GetString(0),
                            RoomID = rdr.GetString(1),
                            SessionDate = rdr.GetString(2),
                            SessionTimeStart = rdr.GetString(3),
                            SessionTimeEnd = rdr.GetString(4)
                        };
                    }
                }
            }
        }
    }
    return sessionDto;
}
  

很多这是手工输入,因为我现在无法访问VS,   但是你应该让它发挥作用。

另外,我使用了rdr.GetString()GetType()还有其他方法。