Caveat: I am new to C# and SQL (less than 2 months with C# and 6 months with SQL)
I have been working on this for a few days, and I am beginning to think I am asking the impossible.
I have two local databases. The first is a Temp database that receives data from a third party. This data is in XML format and does have duplicate records in it.
I insert the data into the Temp database and then would like to use INSERT INTO.. to move the unique records into the Final database.
I have created and tested the insert into sql and it works with no problems. Here is an example:
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))
This works. I have even tried creating a Synonym for Final.dbo.R_DATA, and replaced that in the query – again in SQL Express it also works.
I have also set both queries (with and without the Synonym, as stored procedures, and again they both work from within SQL Express.
I then try to run the same query from C#- using the following.
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 is the sql script I am trying – I converted the above query into a procedure and then placed the procedure in the sql
string script = SQLfile.OpenText().ReadToEnd();
SqlConnection connection = new SqlConnection(sqlConnStr);
connection.Open();
Server server = new Server(new ServerConnection(connection));
I am running this from a form – for testing it is on a button click but I would like it to be part of a longer procedure when / if I get it working. This is for me to see that the connection is open
StatusMessage.AppendText(connection.ServerVersion + " " + connection.State);
server.ConnectionContext.ExecuteNonQuery(script);
connection.Close();
It is at the server.ConnectionContect.ExecuteNonQuery(script); that the error happens – no matter what I try I get an Invalid Object error. I am thinking that there is no way to insert data from a table in one db to another, or am I missing something.
I think I could make this work by:
- extract distinct rows from the Temp.R_DATA to a new tempR_DATA
table in that Temp db. - use bulkcopy to move the whole TempR_DATA
table to the dbo.FINAL - connect to the dbo.Final and run a query
there to insert from the FINAL.dbo.temp.R_DATA into FINAL.dbo.R_DATA
(using where not exists).
But I would realy like to avoid all of those read and writes, as something tells me it would be slow.
So what am I overlooking?
Any and all comments are welcome, I have a feeling that this is an issue of concept (how I am trying to do this) rather than syntax etc.
Conrad asked about the exact error:
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:
Here is the error message – same – Invalid Object, I get this whenever I am trying to do the insert across databases.
Thank you.
This code should work:
Also I recommend to wrap the query within a stored procedure.