SQL Server迁移帮助使用“dbo”创建表。

时间:2011-01-17 20:18:49

标签: sql-server ms-access

我运行SQL Server迁移帮助,仅将我的后端表从Access 2003数据库迁移到SQL Server 2008 Express。现在,当我通过ODBC连接到SQL Server时,我的所有表都被命名为“dbo.tablename”。我现有的所有查询和表单都不使用这些名称。解决此问题的最佳方法是什么?

我是否需要更改架构名称?我将用什么SQL语句来处理这个问题?

1 个答案:

答案 0 :(得分:1)

我做了两件不同的事来解决上面问题中详述的问题。首先,我创建了一个重命名表的例程。后来我决定放弃这个,我写了一个不同的例程(如下所列)来处理数据库启动时表的链接。

Public Sub subChangeLinkedTableNames()

    Dim dbCurr As DAO.Database
    Dim tdfCurr As DAO.TableDef

    Set dbCurr = CurrentDb()

    For Each tdfCurr In dbCurr.TableDefs
        If Len(tdfCurr.Connect) > 0 Then
            If Left(tdfCurr.Name, 4) = "dbo_" Then
                tdfCurr.Name = Replace(tdfCurr.Name, "dbo_", "")
            End If
        End If
    Next


    Set tdfCurr = Nothing
    Set dbCurr = Nothing

End Sub

上面的代码工作正常,但最终我决定编写一个例程,每次打开Access数据库时自动重新链接表。此例程遍历要链接的表列表,并为每个表调用此子。请注意,我正在通过在名为sLocalTableName的变量/参数中指定我希望表具有的名称来解决表命名问题:

Private Sub LinkODBCTable(sSourceTableName As String, sLocalTableName As String, sIndexFields As String, sConString As String)
    Dim dbCurrent As DAO.Database
    Dim tdfCurrent As DAO.TableDef
    Set dbCurrent = DBEngine.Workspaces(0).Databases(0)

    On Error Resume Next
    'Let's not accidentally delete a local table of the same name
    If Len(dbCurrent.TableDefs(sLocalTableName).Connect) > 0 Then
        dbCurrent.TableDefs.Delete sLocalTableName
    End If
    Select Case Err.Number
        Case 0
            'Do Nothing
        Case Else
            Err.Clear
        'Case 3011
            'Table does not exist
    End Select

    Set tdfCurrent = dbCurrent.CreateTableDef(sLocalTableName)
    tdfCurrent.Connect = sConString
    tdfCurrent.SourceTableName = sSourceTableName
    dbCurrent.TableDefs.Append tdfCurrent
    If Err.Number <> 0 Then
        'Sometimes 3010 occurs here and I don't know why. A compact and repair always seems to fix it.
        MsgBox "Error in LinkODBCTable" & vbCrLf & vbCrLf & Err.Number & " " & Err.description
        Err.Clear
    End If

    If sIndexFields <> "" Then
        'sIndexFields should be field names, each enclosed in brackets, comma separated
        'Most of the time it will just be one field
        'This is to tell Access which field(s) is the Primary Key
        dbCurrent.Execute "CREATE INDEX __UniqueIndex ON [" & sLocalTableName & "] (" & sIndexFields & ")", dbFailOnError
        If Err.Number <> 0 Then
            If Err.Number = 3283 Then
                'Primary Key Already Exists
            Else
                MsgBox "Error in LinkODBCTable" & vbCrLf & vbCrLf & Err.Number & " " & Err.description
            End If
            Err.Clear
        End If
    End If

    Set tdfCurrent = Nothing
    Set dbCurrent = Nothing
End Sub