0

请看下面的代码:

Imports System.Data.SqlClient
Imports System.Configuration

    Public Class Form1
        Private _ConString As String
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Dim objDR As SqlDataReader
            Dim objCommand As SqlCommand
            Dim objCon As SqlConnection
            Dim id As Integer
            Try
                _ConString = ConfigurationManager.ConnectionStrings("TestConnection").ToString
                objCon = New SqlConnection(_ConString)
                objCommand = New SqlCommand("SELECT Person.URN, Car.URN FROM Person INNER JOIN Car ON Person.URN = Car.URN AND PersonID=1")
                objCommand.Connection = objCon
                objCon.Open()
                objDR = objCommand.ExecuteReader(ConnectionState.Closed)
                Do While objDR.Read
                    id = objDR("URN") 'line 19
                Loop
                objDR.Close()
            Catch ex As Exception
                Throw
            Finally

            End Try

        End Sub


End Class

请参阅第 19 行。是否可以执行类似的操作:

objDR("Person.URN")

当我这样做时: objDR("URN") 它返回 CarURN 而不是 Person URN。我意识到一种解决方案是使用 SQL AS 关键字,即:

SELECT Person.URN As PersonURN, Car.URN AS CarURN FROM Person INNER JOIN Car ON Person.URN = Car.URN AND PersonID=1

进而:objDR("PersonURN")

但是,由于应用程序的设计方式,我想尽可能避免这种情况,即它会涉及大量的硬编码。

4

3 回答 3

2

您可以按索引而不是按名称查找列。以下任一方法都可以:

id = objDR(0)
id = objDR.GetInt32(0)

否则,您最好的选择是使用“As”关键字或双引号(这是 ansi 标准)来创建别名。

于 2013-08-12T18:38:25.147 回答
0

在您的情况下,由于内部连接,您不需要在 select 子句中包含两者,因为需要相等,所以只包含其中一个。

所以要么

SELECT Person.URN 
FROM   Person INNER JOIN 
       Car ON Person.URN = Car.URN AND PersonID=1

或者

SELECT Car.URN 
FROM   Person INNER JOIN 
       Car ON Person.URN = Car.URN AND PersonID=1
于 2013-08-12T18:40:10.930 回答
0

如果您已经在更改查询,并且由于某种原因无法更改其他代码,则使用您喜欢的列名创建一个视图,然后从该视图中选择。

于 2013-08-12T18:40:26.337 回答