为什么这个查询会抛出异常?

发布于 2024-11-04 06:33:41 字数 8480 浏览 0 评论 0原文

这是代码:

DataTable ds = new DataTable();
SqlConnection cons = new SqlConnection(strConnString);
SqlDataAdapter ad = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
cons.Open();
string strQuery = "SELECT" +
    "  material," +
    "  SUM([Amount]) AS [Amount]," +
    "  Dates = RIGHT(CONVERT(varchar(50), [date_in], 106), 8) " +
    "INTO #TMP " +
    "FROM " +
    "  [rec_stats] " +
    "GROUP BY " +
    "  material," +
    "  RIGHT(CONVERT(varchar(50), [date_in], 106), 8) " +
    "ORDER BY " +
    "  material, min ([date_in])"+
    "SELECT DATES," +
    "       SUM(CASE material WHEN 0 THEN Amount ELSE 0 END)AS PAPER," +
    "       SUM(CASE material WHEN 1 THEN Amount ELSE 0 END)AS PLASTIC," +
    "       SUM(CASE material WHEN 2 THEN Amount ELSE 0 END)AS GLASS," +
    "       SUM(CASE material WHEN 3 THEN Amount ELSE 0 END)AS METALS," +
    "       SUM(CASE material WHEN 4 THEN Amount ELSE 0 END)AS FABRIC" +
    "FROM #TMP" +
    "GROUP BY DATES";

cmd.CommandText = strQuery;         
cmd.Connection = cons;
ad.SelectCommand = cmd;

try
{
    ad.Fill(ds);
}
catch (Exception d)
{
    MessageBox.Show("CRAP!! " + d.ToString());
}
string dropper = "DROP TABLE #TMP";
cmd.CommandText = dropper;
cmd.ExecuteNonQuery();
cons.Close();

fill 函数抛出了 sqlException,知道问题出在哪里吗?

这是一个例外:

System.Windows.Markup.XamlParseException was unhandled
  Message='The invocation of the constructor on type 'RecyclingStats.MainWindow' that matches the specified binding constraints threw an exception.' Line number '4' and line position '9'.
  Source=PresentationFramework
  LineNumber=4
  LinePosition=9
  StackTrace:
       at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
       at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
       at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
       at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
       at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
       at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
       at System.Windows.Application.DoStartup()
       at System.Windows.Application.<.ctor>b__1(Object unused)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.DispatcherOperation.InvokeImpl()
       at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, 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.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.ProcessQueue()
       at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at RecyclingStats.App.Main() in G:\Learning\RecyclingStats\RecyclingStats\obj\x86\Debug\App.g.cs:line 0
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       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: System.Data.SqlClient.SqlException
       Message=Incorrect syntax near '#TMPGROUP'.
       Source=.Net SqlClient Data Provider
       ErrorCode=-2146232060
       Class=15
       LineNumber=1
       Number=102
       Procedure=""
       Server=localhost
       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.SqlDataReader.ConsumeMetaData()
            at System.Data.SqlClient.SqlDataReader.get_MetaData()
            at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
            at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
            at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
            at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
            at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
            at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
            at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
            at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
            at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
            at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
            at RecyclingStats.MainWindow.setChartData() in G:\Learning\RecyclingStats\RecyclingStats\MainWindow.xaml.cs:line 333
            at RecyclingStats.MainWindow..ctor() in G:\Try\MainWindow.xaml.cs:line 44
       InnerException: 

here is the code:

DataTable ds = new DataTable();
SqlConnection cons = new SqlConnection(strConnString);
SqlDataAdapter ad = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
cons.Open();
string strQuery = "SELECT" +
    "  material," +
    "  SUM([Amount]) AS [Amount]," +
    "  Dates = RIGHT(CONVERT(varchar(50), [date_in], 106), 8) " +
    "INTO #TMP " +
    "FROM " +
    "  [rec_stats] " +
    "GROUP BY " +
    "  material," +
    "  RIGHT(CONVERT(varchar(50), [date_in], 106), 8) " +
    "ORDER BY " +
    "  material, min ([date_in])"+
    "SELECT DATES," +
    "       SUM(CASE material WHEN 0 THEN Amount ELSE 0 END)AS PAPER," +
    "       SUM(CASE material WHEN 1 THEN Amount ELSE 0 END)AS PLASTIC," +
    "       SUM(CASE material WHEN 2 THEN Amount ELSE 0 END)AS GLASS," +
    "       SUM(CASE material WHEN 3 THEN Amount ELSE 0 END)AS METALS," +
    "       SUM(CASE material WHEN 4 THEN Amount ELSE 0 END)AS FABRIC" +
    "FROM #TMP" +
    "GROUP BY DATES";

cmd.CommandText = strQuery;         
cmd.Connection = cons;
ad.SelectCommand = cmd;

try
{
    ad.Fill(ds);
}
catch (Exception d)
{
    MessageBox.Show("CRAP!! " + d.ToString());
}
string dropper = "DROP TABLE #TMP";
cmd.CommandText = dropper;
cmd.ExecuteNonQuery();
cons.Close();

the fill function thrown an sqlexception, any idea where is the problem?

here is the exception:

System.Windows.Markup.XamlParseException was unhandled
  Message='The invocation of the constructor on type 'RecyclingStats.MainWindow' that matches the specified binding constraints threw an exception.' Line number '4' and line position '9'.
  Source=PresentationFramework
  LineNumber=4
  LinePosition=9
  StackTrace:
       at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
       at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
       at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
       at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
       at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
       at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
       at System.Windows.Application.DoStartup()
       at System.Windows.Application.<.ctor>b__1(Object unused)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.DispatcherOperation.InvokeImpl()
       at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, 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.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.ProcessQueue()
       at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at RecyclingStats.App.Main() in G:\Learning\RecyclingStats\RecyclingStats\obj\x86\Debug\App.g.cs:line 0
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       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: System.Data.SqlClient.SqlException
       Message=Incorrect syntax near '#TMPGROUP'.
       Source=.Net SqlClient Data Provider
       ErrorCode=-2146232060
       Class=15
       LineNumber=1
       Number=102
       Procedure=""
       Server=localhost
       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.SqlDataReader.ConsumeMetaData()
            at System.Data.SqlClient.SqlDataReader.get_MetaData()
            at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
            at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
            at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
            at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
            at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
            at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
            at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
            at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
            at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
            at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
            at RecyclingStats.MainWindow.setChartData() in G:\Learning\RecyclingStats\RecyclingStats\MainWindow.xaml.cs:line 333
            at RecyclingStats.MainWindow..ctor() in G:\Try\MainWindow.xaml.cs:line 44
       InnerException: 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

唔猫 2024-11-11 06:33:41

这是带有适当空格的完整查询:

string strQuery = "SELECT " +
    "  material, " +
    "  SUM([Amount]) AS [Amount], " +
    "  Dates = RIGHT(CONVERT(varchar(50), [date_in], 106), 8) " +
    "INTO #TMP " +
    "FROM " +
    "  [rec_stats] " +
    "GROUP BY " +
    "  material, " +
    "  RIGHT(CONVERT(varchar(50), [date_in], 106), 8) " +
    "ORDER BY " +
    "  material, min ([date_in])"+
    "SELECT DATES, " +
    "       SUM(CASE material WHEN 0 THEN Amount ELSE 0 END)AS PAPER, " +
    "       SUM(CASE material WHEN 1 THEN Amount ELSE 0 END)AS PLASTIC, " +
    "       SUM(CASE material WHEN 2 THEN Amount ELSE 0 END)AS GLASS, " +
    "       SUM(CASE material WHEN 3 THEN Amount ELSE 0 END)AS METALS, " +
    "       SUM(CASE material WHEN 4 THEN Amount ELSE 0 END)AS FABRIC " +
    "FROM #TMP " +
    "GROUP BY DATES";

没有空格:

"FROM #TMP " +
"GROUP BY DATES";

但你有

"FROM #TMP" +
"GROUP BY DATES";

它变成 "FROM #TMPGROUP BY DATES";

Here is full query with proper spaces:

string strQuery = "SELECT " +
    "  material, " +
    "  SUM([Amount]) AS [Amount], " +
    "  Dates = RIGHT(CONVERT(varchar(50), [date_in], 106), 8) " +
    "INTO #TMP " +
    "FROM " +
    "  [rec_stats] " +
    "GROUP BY " +
    "  material, " +
    "  RIGHT(CONVERT(varchar(50), [date_in], 106), 8) " +
    "ORDER BY " +
    "  material, min ([date_in])"+
    "SELECT DATES, " +
    "       SUM(CASE material WHEN 0 THEN Amount ELSE 0 END)AS PAPER, " +
    "       SUM(CASE material WHEN 1 THEN Amount ELSE 0 END)AS PLASTIC, " +
    "       SUM(CASE material WHEN 2 THEN Amount ELSE 0 END)AS GLASS, " +
    "       SUM(CASE material WHEN 3 THEN Amount ELSE 0 END)AS METALS, " +
    "       SUM(CASE material WHEN 4 THEN Amount ELSE 0 END)AS FABRIC " +
    "FROM #TMP " +
    "GROUP BY DATES";

there is no space:

"FROM #TMP " +
"GROUP BY DATES";

but you have

"FROM #TMP" +
"GROUP BY DATES";

which turns into "FROM #TMPGROUP BY DATES";

秋风の叶未落 2024-11-11 06:33:41

“FROM #TMP” +

您需要一个空间。

"FROM #TMP " +

You need a space.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文