无法比较SQL和数据表并将新条目复制到sql表

时间:2014-11-18 18:26:38

标签: sql sql-server vb.net datatable sqlbulkcopy

我尝试在VB.NET中的SQL Server 2012数据库上运行左连接,但我仍然坚持使用这段代码:

Dim dtTabelle1 as DataTable
(first Column of dtTabelle1 = Zyklus ID)

Dim con As SqlConnection
Dim conString, cmdString As String
Dim cmd As SqlClient.SqlCommand

conString = "path"
con = New SqlConnection(conString)
con.Open()

dtTabelle1.TableName = "Test"

cmdString = "INSERT INTO Daten ([Zyklus ID])" & _
                "Select [Zyklus ID]" & _
                "FROM Test " & _
                "LEFT JOIN Daten ON (Test.[Zyklus ID] = Daten.[Zyklus ID])" & _
                    "WHERE (Daten.[Zyklus ID] IS NULL);"

cmd = New SqlCommand(cmdString, con)
cmd.CommandType = CommandType.Text

cmd.ExecuteNonQuery()
con.Close()

我收到错误:

  

无效的对象名称'测试'

(顺便说一句,我无法更改" Zyklus ID" :()中的空白。

dtTabelle1已填充且架构与服务器Daten上的目标数据库相同。

2 个答案:

答案 0 :(得分:0)

如果您使用别名表格

会更好

试试这样:

cmdString = "INSERT INTO Daten ([Zyklus ID])" & _
                "Select T.[Zyklus ID]" & _
                "FROM Test T " & _
                "LEFT JOIN Daten D ON (T.[Zyklus ID] = D.[Zyklus ID])" & _
                    "WHERE (D.[Zyklus ID] IS NULL);"

答案 1 :(得分:0)

请在查询的SQL语句之间放置适当的空格

cmdString = "INSERT INTO Daten ([Zyklus ID]) " & _
            "SELECT [Zyklus ID] " & _
            "FROM Test " & _
            "LEFT JOIN Daten ON (Test.[Zyklus ID] = Daten.[Zyklus ID]) " & _
            "WHERE (Daten.[Zyklus ID] IS NULL);"