警告:我是C#和SQL的新手(使用C#不到2个月,使用SQL需要6个月)
我已经为此工作了几天,我开始认为我在问这个不可能的事情。
我有两个本地数据库。第一个是Temp数据库,它接收来自第三方的数据。此数据采用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(脚本);错误发生 - 无论我尝试什么,我都会收到无效对象错误。我在想,没有办法将数据从一个数据库中的表插入到另一个数据库中,或者我错过了什么。 我想我可以通过以下方式完成这项工作:
但我真的希望避免所有这些读写操作,因为有些东西告诉我它会很慢。
那我在俯瞰什么? 欢迎任何和所有评论,我有一种感觉,这是一个概念问题(我如何尝试这样做)而不是语法等。
康拉德询问了确切的错误:
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:
这是错误消息 - 相同 - 无效对象,每当我尝试跨数据库插入时,我都会得到这个。 谢谢。
答案 0 :(得分: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
}
我还建议将查询包装在存储过程中。