SQL Server - 具有重复名称的多选

时间:2010-03-07 01:10:59

标签: sql vb.net select

我正试图从我的SQL数据库中获取一些数据,如下所示;

USE exampleDatabase
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC

问题是,当我读取数据时,我收到错误“名称”。

Dim byWeight As String = sqlReader.GetValue(sqlReader.GetOrdinal("Name"))
Dim byAge As String = sqlReader.GetValue(sqlReader.GetOrdinal("Name"))

考虑到我不能两次使用名字,我如何阅读上述数据?

4 个答案:

答案 0 :(得分:1)

我认为你在第一个SELECT语句后丢失了一个分号。这是我放在一起的示例应用程序(请注意我的sql语句中的分号):

var sql = "Select TOP 1 name from sys.columns;"
          + "Select TOP 1 name from sys.objects";

var firstname = string.Empty;
var secondname = string.Empty;

var connString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
using ( var conn = new SqlConnection( connString ) )
{
    conn.Open();
    using ( var cmd = new SqlCommand( sql, conn ) )
    {
        var reader = cmd.ExecuteReader();
        if ( reader == null )
            return;
        if ( reader.Read() )
            firstname = reader.GetString( reader.GetOrdinal( "Name" ) );

        reader.NextResult();
        if ( reader.Read() )
            secondname = reader.GetString( reader.GetOrdinal( "Name" ) );

    }
}

Response.Write( firstname + "<br />" );
Response.Write( secondname + "<br />" );

您可以使用“GO关键字”来实现与分号相同的目标:

    var sql = "Select TOP (1) name from sys.columns GO "
              + "Select TOP (1) name from sys.objects";

答案 1 :(得分:0)

您可以使用'as'关键字重命名结果中的列,如下所示:

SELECT TOP(1) [Name] AS ByWeight FROM [Peeps] ORDER BY [Weight] DESC

答案 2 :(得分:0)

嗯...嗯,你可以把它作为一个选择声明......

USE exampleDatabase

SELECT W.[Name] AS W_Name,  A.[Name] AS A_Name FROM
(SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC) W 
JOIN (SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC) A

答案 3 :(得分:0)

如果将SQL一起联合到一个结果集中会怎样?

USE exampleDatabase
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC
UNION ALL
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC