2014-09-26 57 views
-8

我的代碼有什麼問題......我嘗試了幾件事情,但一次又一次地得到相同的錯誤。數據庫中已有一個對象異常

任何幫助? 的代碼是:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[SubDomainName].ToString()); 
conn.Open(); 
string temptable = "CREATE TABLE [dbo].[Tmptablenew]([TicketID] [int] NULL,[TicketDescription][varchar](max) NULL,[TicketAssignedTo] [varchar](100) NULL,[TicketCreatedDate] [datetime] NULL,[TicketStatus][varchar](50),CRMConnectionID [int] NULL,[TicketUpdatedDate] [Datetime] NULL,img [varchar](500) NULL)"; 
SqlCommand cmd = new SqlCommand(temptable, conn); 
cmd.ExecuteNonQuery(); 
SqlCommand cmmd = new SqlCommand("select * from Tickets", conn); 
SqlDataAdapter adapter = new SqlDataAdapter(cmmd); 
DataTable dt1 = new DataTable("dt1"); 
adapter.Fill(dt1); 
cmmd.ExecuteNonQuery(); 

//BulkCopy the data in the DataTable to the temp table 
using (SqlBulkCopy bulk = new SqlBulkCopy(conn)) 
{ 
    bulk.DestinationTableName = "Tmptablenew"; 
    bulk.WriteToServer(result); 
    conn.Close(); 
} 
conn.Open(); 
string mergeSql = "merge into Tickets as Target " + 
        "using Tmptablenew as Source " + 
        "on " + 
        "Target.TicketID= Source.TicketID " + 
        "and Target.CRMConnectionID = Source.CRMConnectionID " + 
        "when not matched then " + 
        "insert (TicketID,TicketDescription,TicketAssignedTo,TicketCreatedDate,TicketStatus,CRMConnectionID,TicketUpdatedDate,img) values (Source.TicketID,Source.TicketDescription,Source.TicketAssignedTo,Source.TicketCreatedDate,Source.TicketStatus,Source.CRMConnectionID,Source.TicketUpdatedDate,Source.img);"; 

string mergesql1 = "Update Tickets SET TicketDescription=S.TicketDescription, TicketAssignedTo = S.TicketAssignedTo, TicketStatus = S.TicketStatus,TicketUpdatedDate = S.TicketUpdatedDate,img = S.img FROM Tickets t JOIN Tmptablenew AS S ON t.TicketID = S.TicketID and T.CRMConnectionID = S.CRMConnectionID"; 
cmd.CommandText = mergeSql; 
cmd.ExecuteNonQuery(); 
cmmd.CommandText = mergesql1; 
cmmd.ExecuteNonQuery(); 
cmd.CommandText = "drop table Tmptablenew"; 
cmd.ExecuteNonQuery(); 
//Clean up the temp table 
conn.Close(); 
+1

做一些代碼並描述問題,請 – lenden 2014-09-26 12:46:43

+0

什麼是_error_?在哪一行?我們需要更多的細節.. – 2014-09-26 12:49:03

+1

很明顯,「數據庫中已有一個對象」。您無法創建與已存在的對象同名的對象。因此,要麼擺脫已經存在的或不要嘗試創建一個新的。 – David 2014-09-26 12:51:03

回答

1

你正在創建表Tmptablenew,它看起來像這樣表數據庫alredy存在。

我想,你正在嘗試創建一個臨時表,在這種情況下爲MySQL創建它爲CREATE TEMPORARY TABLE,或者爲MS SQL使用表名#Tmptablenew。在這種情況下,會話關閉時也會自動放棄。

編輯

所以,你必須改變string temptable = "CREATE TEMPORARY TABLE [dbo].[Tmptablenew]([TicketID]...等等,如果你正在使用MySQL的(根據你的問題的標記)。或者如果它是MS SQL(如我懷疑)然後string temptable = "CREATE TABLE [dbo].[#Tmptablenew]([TicketID]...等等(在這種情況下,你應該在你的代碼中將它命名爲#Tmptablenew)。

+0

哪個查詢部分應該在那裏改變?對於這個C#和sql來說是新的。 – user3226735 2014-09-26 13:06:24

+0

我並不熟練使用My SQL,但Google會幫助您在此處加載以瞭解如何創建此功能。 http://dev.mysql.com/doc/refman/5.1/en/create-table.html – alykins 2014-09-26 13:11:47

+0

@ user3226735我已經更新了答案 – 2014-09-26 13:19:42

相關問題