所选列的总数

时间:2014-12-06 17:54:56

标签: sql asp.net sql-server

我试图从45列中获得43个总数。在表中,它们被定义为整数。

   Dim connStr, cmdStr As String
   connStr = ConfigurationManager.ConnectionStrings("astsql").ConnectionString
   cmdStr = "SELECT (SUM([index]),SUM([01]),SUM([02]),SUM([03]),SUM([04]),SUM([05]),SUM([06]),SUM([07]),SUM([08]),SUM([09]),SUM([10]),SUM([11]),SUM([12]),SUM([13]),SUM([14]),SUM([15]),SUM([16]),SUM([17]),SUM([18]),SUM([19]),SUM([20]),SUM([aa]),SUM([ab]),SUM([ac]),SUM([ad]),SUM([ae]),SUM([af]),SUM([ag]),SUM([ah]),SUM([ai]),SUM([aj]),SUM([ak]),SUM([al]),SUM([am]),SUM([an]),SUM([ao]),SUM([ap]),SUM([aq]),SUM([ar]),SUM([as]),SUM([at]),SUM([grsc]),SUM([grkr]),SUM([grkn])) FROM [count];"
    Dim totalcount As Integer = 0
    Dim n As Integer = 0
    Try
        Using conn As New SqlConnection(connStr)
            Using cmd As New SqlCommand(cmdStr, conn)
                conn.Open()
                cmd.ExecuteNonQuery()
                Using myreader = cmd.ExecuteReader()
                    While myreader.Read()
                        totalcount = totalcount + Convert.ToInt32(myreader(n))
                        n = n + 1
                    End While
                End Using
                conn.Close()
                cmd.Dispose()
                conn.Dispose()
            End Using
        End Using
    Catch ex As Exception
        Label5.Text = ex.ToString()
    End Try

这是我的错误代码:

  

System.Data.SqlClient.SqlException(0x80131904):'附近的语法不正确,'。
  在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔breakConnection,Action 1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction)
  在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,Boolean callerHasConnectionLock,Boolean asyncClose)
  在System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,SqlCommand cmdHandler,SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj,Boolean& dataReady)
  在System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName,Boolean async,Int32 timeout,Boolean asyncWrite)
  在System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1完成

1 个答案:

答案 0 :(得分:1)

除非您添加SUM,否则不应将cmdStr = "SELECT (SUM([index])+SUM([01])+SUM([02])+SUM([03])+SUM([04])...) FROM [count];" 括在括号中。用加号替换逗号将解决问题:

ExecuteScalar

现在您的查询返回一个号码,因此您可以使用ExecuteReader代替conn.Open() totalcount = Convert.ToInt32(cmd.ExecuteScalar()) conn.Close()

{{1}}