简体   繁体   English

替代T-SQL AS关键字

[英]Alternative to the T-SQL AS keyword

Please see the code below: 请参阅以下代码:

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

Please see line 19. Is it possible to do something similar to this: 请参阅第19行。是否可以执行与此类似的操作:

objDR("Person.URN")

When I do: objDR("URN") it returns the CarURN and not the Person URN. 当我这样做:objDR(“URN”)它返回CarURN而不是Person URN。 I realise that one solution would be to use the SQL AS keyword ie: 我意识到一个解决方案是使用SQL AS关键字,即:

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

and then: objDR("PersonURN") 然后: objDR("PersonURN")

However, I want to avoid this if possible because of the way the app is designed ie it would involve a lot of hard coding. 但是,如果可能的话,我想避免这种情况,因为应用程序的设计方式,即它将涉及大量的硬编码。

You can look up the column by index, rather than by name. 您可以按索引查找列,而不是按名称查找。 Either of the following would work: 以下任何一种都可以工作:

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

Otherwise, your best bet is the "As" keyword or double-quotes (which are the ansi standard) to create an alias. 否则,最好的选择是创建别名的“As”关键字或双引号(这是ansi标准)。

In your case, becuase of the inner join, you do not need to include both in the select clause, as equality is required, so only include either one. 在您的情况下,由于内部联接,您不需要在select子句中包含两者,因为需要相等,因此只包括其中一个。

So either 所以要么

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

or 要么

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM