2

我基本上在 T-SQL 中设置了一个从 Excel 导入 SQL 的过程:

SELECT *  FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;HDR=YES;Database=C:\report.xls','select * from [name555$]')

name555 由一个固定的名称组成,而 555 似乎是一个随机的三位数。当报告来找我时,有时名字是 555,有时是 439、390 等等。

有没有办法指示 SQL 服务器(最好在 T-SQL 中,因为这就是我现在正在使用的)动态读取名称?这是 XLS 文件中唯一的工作表,但它

例如,在 VBA 中,您可以将工作表用作 name1$ 名称或“sheet1$”索引。好吧,我希望有人可以帮助解决这个问题:)

4

1 回答 1

1

您可以查询工作簿的 SCHEMA 以检索 TABLE(工作表)名称。如果您的工作簿中只有一个工作表,则第一个有效的 TABLE_NAME 将是您的工作表的名称。

下面给出(在 VB.NET 代码中)是我一直用于此类任务的辅助方法。该函数的返回值为您将名称放在括号中,因此可以在 SQL 语句中使用它。

''' <summary>
''' Returns the name of the first worksheet in an Excel workbook.
''' </summary>
''' <param name="connectString">OleDb connection string for an Excel workbook.</param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function GetTableName(ByVal connectString As String) As String

  Dim dtSheets As New DataTable
  Dim tmp As String = ""

  Using cn As New OleDbConnection(connectString)
     cn.Open()
     dtSheets = cn.GetSchema("Tables")
  End Using

  For Each rw As DataRow In dtSheets.Rows
     'Get the name of the first worksheet in the file that ends
     'with a $.
     tmp = rw("TABLE_NAME")
     'Check to see if the table name is surrounded by apostorphes.
     If tmp.StartsWith("'") And tmp.EndsWith("'") Then
        'Remove the apostrophes.
        tmp = tmp.TrimEnd("'")
        tmp = tmp.TrimStart("'")
     End If

     If tmp.EndsWith("$") Then
        Exit For
     Else
        tmp = ""
     End If
  Next

  Return "[" & tmp & "]"

End Function
于 2013-08-07T19:18:48.687 回答