使用包含撇号的vba字符串变量运行sql select命令

时间:2019-07-15 19:16:47

标签: sql sql-server excel vba

使用VBA,我正在尝试从SQL表中选择数据,但是由于我要查找的客户名称包含撇号(McDonald's)而遇到了问题。我尝试不使用replace函数,而是尝试将customerName设置为参数,以避免出现此问题。

    Dim rs As ADODB.Recordset
    Set rs = New ADODB.Recordset
    Dim cmd As New ADODB.Command
        customerName = .Range("customerName")

        queryCustomers = "select * from Customers where CustomerName = '" & customerName & "'"

        'Open a connection to SQL Server
        conn.Open cnstring

        With cmd
         .CommandText = queryCustomers
         .Parameters.Append .CreateParameter("@param1", adVarChar, adParamInput, 50, customerName)
         .ActiveConnection = conn
         .CommandType = adCmdText
        End With

        Set rs = cmd.Execute

由于撇号,我遇到相同的错误,这意味着我使用的参数设置不正确。总之,我需要帮助以使我的queryCustomers字符串将customerName作为参数传递,以便customerName中的撇号不会影响SQL命令。

1 个答案:

答案 0 :(得分:1)

您的

queryCustomers = "select * from Customers where CustomerName = '" & customerName & "'"

获得评估

"select * from Customers where CustomerName = 'McDonald's'"

没有变量可以放置值。这就是执行

尝试这样的事情

cmd.CommandText = "select * from Customers where CustomerName = @Value1"
Dim param1 As ADODB.Parameter
Set param1 = cmd.CreateParameter("@Value1", adVarWChar, adParamInput, 8, "McDonald's")
cmd.Parameters.Append param1

这种方法应该可以自动逃脱麦当劳->麦当劳。