TSQL合并'附近的语法不正确,'

时间:2014-06-21 09:13:43

标签: c# sql-server-2008 tsql

获得SQLException"超级有用"异常消息(',&#39 ;.附近的语法不正确),想知道是否有人可以看到glace的语法有什么问题?

这是基于示例的代码,可以在http://www.jarloo.com/c-bulk-upsert-to-sql-server-tutorial/

找到
  private void importToolStripMenuItem_Click(object sender, EventArgs e)
  {
        DataTable import = new DataTable();
        DialogResult result = this.importFileDialog.ShowDialog();
        if (DialogResult.OK == result)
        {
            Stream importStream = this.importFileDialog.OpenFile();
            import.ReadXml(importStream);
            importStream.Close();

            string tmpTable = "select top 0 * into #import from tblJob;";

            using (SqlConnection con = new SqlConnection(CONSTRING))
            {
                con.Open();

                SqlCommand cmd = new SqlCommand(tmpTable, con);
                cmd.ExecuteNonQuery();

                SqlBulkCopyOptions options = SqlBulkCopyOptions.KeepIdentity;

                using (SqlBulkCopy bulk = new SqlBulkCopy(con))
                {
                    bulk.DestinationTableName = "#import";
                    bulk.WriteToServer(import);
                }

                //http://www.jarloo.com/c-bulk-upsert-to-sql-server-tutorial/
                //Now use the merge command to upsert from the temp table to the production table
                string mergeSql = "merge into tblJob as Target " +
                                  "using #import as Source " +
                                  "on " +
                                  "Target.[Location]=Source.[Location]," +
                                  "Target.[Schedule]=Source.[Schedule] " +
                                  "when matched then " +
                                  "update set Target.[Complete]=Source.[Complete]," +
                                  "Target.[Cost]=Source.[Cost]," +
                                  "Target.[Description]=Source.[Description]";
                                  //"when not matched then " +
                                  //"insert (Symbol,Price,Timestamp) values (Source.Symbol,Source.Price,Source.Timestamp)" +
                                  //";";

                cmd.CommandText = mergeSql;
                cmd.ExecuteNonQuery();

                //Clean up the temp table
                cmd.CommandText = "drop table #import";
                cmd.ExecuteNonQuery();
            }
            dgvJobs.DataSource = getData("select * from tblJob");

1 个答案:

答案 0 :(得分:5)

如果您希望MERGE中有多个加入条件,则需要使用AND关键字(而不是逗号,,因为您现在正在使用)。

而不是

merge into tblJob as Target 
using #import as Source on Target.[Location]=Source.[Location], Target.[Schedule]=Source.[Schedule] 

您正在使用,请改用:

MERGE INTO dbo.tblJob AS Target 
USING #import AS Source ON Target.[Location] = Source.[Location]
                           AND Target.[Schedule] = Source.[Schedule] 

对于任何加入条件,也适用于INNER JOINLEFT OUTER JOIN或任何其他加入类型。