替代T-SQL AS关键字

时间:2013-08-12 18:35:41

标签: sql vb.net

请参阅以下代码:

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")

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

3 个答案:

答案 0 :(得分:2)

您可以按索引查找列,而不是按名称查找。以下任何一种都可以使用:

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

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

答案 1 :(得分: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

答案 2 :(得分:0)

如果您已经在更改查询,并且由于某种原因无法更改其他代码,则可以根据需要创建包含列名的视图,然后从该视图中进行选择。