如何在 VBA 中转义 PostgreSQL 的数据库表名和列名?

问题描述 投票:0回答:1
我正在尝试将Access数据库迁移到PostgreSQL数据库,并且很多表名或列名都有空格或数字,例如表名:“test history”和“123 people”,列名:“test历史”。由于这些空格和数字,我不断收到 SQL 语法错误。

'create tables in PostgreSQL database Dim tdf As DAO.TableDef For Each tdf In CurrentDb.TableDefs If Left(tdf.Name, 4) <> "MSys" Then Dim strCreateTable As String strCreateTable = "CREATE TABLE " & tdf.Name & " (" For Each fld In tdf.fields strCreateTable = strCreateTable & fld.Name & " " & GetPostgreSQLDataType(fld.Type) & "," Next fld strCreateTable = Left(strCreateTable, Len(strCreateTable) - 1) & ")" 'MsgBox strCreateTable cnn.Execute strCreateTable End If Next tdf
只是想知道是否有办法将表名和列名的输出转换为字符串。

vba string postgresql ms-access data-migration
1个回答
0
投票
我正在尝试将 Access 数据库迁移到 PostgreSQL 数据库

(我认为 MS Access 需要有尊严地死去,而不是再循环 20 年...)

很多表名或列名都带有空格或数字,例如表名:“

test history

”和“
123 people
”,列名:“
test history
”。由于这些空格和数字,我不断收到 SQL 语法错误。

PostgreSQL 遵循 ANSI/ISO SQL,因此它使用双引号 "

 来分隔对象标识符
,而 Access(又名 JET RedACE)使用方括号 []
.

所以这只是确保您的 SQL 字符串中的对象标识符在 VBA 字符串中用

"

分隔的问题 - 这不是那么糟糕,因为 VBA 在字符串中使用"" 作为转义序列对于双引号。
所以这应该适合你(我还添加了一些额外的空格和 

NULL/

NOT NULL` 处理):

Sub GenerateAndExecuteCreateTableStatements()

    ' Create tables in PostgreSQL database
    Dim tdf As DAO.TableDef
    For Each tdf In CurrentDb.TableDefs
        If Left(tdf.Name, 4) <> "MSys" Then
        
           Dim createStmt As String
            createStmt = GetCreateTableSql(tdf)

            ' Consider using Debug.Print instead of MsgBox to dump variables:
            Debug.Print createStmt
            cnn.Execute createStmt

        End If
    Next tdf

End Sub

Function GetCreateTableSql(tbl As DAO.TableDef)

    Dim createStmt As String
    createStmt = "CREATE TABLE """ &  tdf.Name  & """ ("
    
    Dim fld As DAO.Field
    For Each fld In tdf.Fields

        Dim column As String
        column = vbTab & """" & fld.Name & """" & " " & GetPostgreSQLDataType(fld.Type) & Iif(fld.Required, " NOT NULL", " NULL")

        createStmt = createStmt & column & "," & vbCrLf
     Next
     
    ' Trim trailing comma and add closing parenthesis:
    createStmt = Left(createStmt, Len(createStmt) - 1) & ")"

    ' Return it:
    GetCreateTableSql = createStmt

End Function

© www.soinside.com 2019 - 2024. All rights reserved.