2

警告:我是 C# 和 SQL 的新手(使用 C# 不到 2 个月,使用 SQL 不到 6 个月)

我已经为此工作了几天,我开始认为我在问不可能的事情。

我有两个本地数据库。第一个是从第三方接收数据的临时数据库。此数据采用 XML 格式,并且其中确实有重复记录。

我将数据插入 Temp 数据库,然后想使用 INSERT INTO.. 将唯一记录移动到 Final 数据库中。

我已经创建并测试了插入到 sql 中的内容,它可以正常工作。这是一个例子:

INSERT INTO Final.dbo.R_DATA
(C1, C2,..)
SELECT distinct     C1, C2, ...
FROM Temp.dbo.R_DATA
WHERE NOT EXISTS(Select *
FROM Final.dbo.R_DATA
WHERE (R_DATA.C1=Final.dbo.R_DATA.C1))

这行得通。我什至尝试为 Final.dbo.R_DATA 创建一个同义词,并在查询中替换它——再次在 SQL Express 中它也可以工作。我还设置了两个查询(有和没有同义词,作为存储过程,并且它们都在 SQL Express 中工作。

然后我尝试使用以下命令从 C# 运行相同的查询。

string sqlConnStr = @"DataSource=.\SQLEXPRESS;AttachDbFilename=W:\SQL\**Temp.mdf;Integrated Security=True;Connect Timeout=120;User Instance=True";
FileInfo SQLfile = new FileInfo(@"W:\SQL\MOVETEST.sql");

MOVETEST 是我正在尝试的 sql 脚本 - 我将上述查询转换为一个过程,然后将该过程放在 sql 中

string script = SQLfile.OpenText().ReadToEnd();
SqlConnection connection = new SqlConnection(sqlConnStr);
connection.Open();
Server server = new Server(new ServerConnection(connection));

我正在从一个表单中运行它——为了测试它是在一个按钮点击上,但我希望它成为一个更长的过程的一部分,当/如果我让它工作。这是为了让我看到连接是打开的

StatusMessage.AppendText(connection.ServerVersion + " " + connection.State);
server.ConnectionContext.ExecuteNonQuery(script);
connection.Close();

它在 server.ConnectionContect.ExecuteNonQuery(script); 错误发生 - 无论我尝试什么,我都会收到无效对象错误。我在想没有办法将数据从一个数据库中的表插入到另一个数据库中,或者我错过了什么。我想我可以通过以下方式完成这项工作:

  1. 将 Temp.R_DATA 中的不同行提取到该 Temp db 中的新 tempR_DATA 表中。
  2. 使用 bulkcopy 将整个 TempR_DATA 表移动到 dbo.FINAL
  3. 连接到 dbo.Final 并在那里运行查询以从 FINAL.dbo.temp.R_DATA 插入 FINAL.dbo.R_DATA (使用 where not exists)。

但我真的很想避免所有这些读写,因为有些事情告诉我它会很慢。

那么我忽略了什么?欢迎任何和所有评论,我觉得这是一个概念问题(我如何尝试这样做)而不是语法等。

康拉德询问了确切的错误:

System.Data.SqlClient.SqlException was unhandled   Message=Invalid object name '**Final.dbo.RELEASE_DATA'.   Source=.Net SqlClient Data Provider   ErrorCode=-2146232060   Class=16   LineNumber=3   Number=208   Procedure=MoveRELEASE_DATA   Server=\\.\pipe\37E36041-6FB1-4D\tsql\query   State=1   StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at DataLoader.Imports.button2_Click(Object sender, EventArgs e) in c:\mydocs\visual studio 2010\Projects\PathFinder\PathFinder\Imports.cs:line 363
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at DataLoader.Program.Main() in c:\mydocs\visual studio 2010\Projects\PathFinder\PathFinder\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
       at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
       at System.Activator.CreateInstance(ActivationContext activationContext)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)        
   at System.Threading.ThreadHelper.ThreadStart()   InnerException:

这是错误消息-相同-无效对象,每当我尝试跨数据库插入时都会收到此消息。谢谢你。

4

1 回答 1

3

此代码应该可以工作:

using (SqlConnection connection = new SqlConnection("DataSource=..."))
using (SqlComamnd command = connection.CreateCommand())
{
    command.CommandText = "INSERT INTO ...";

    connection.Open();
    int i = command.ExecuteNonQuery(); // number of rows inserted
}

我还建议将查询包装在存储过程中。

于 2012-06-08T15:15:00.630 回答