2014-12-06 51 views
1

我想要總計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,動作1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction)
在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,布爾callerHasConnectionLock,布爾asyncClose)
在系統.Data.SqlClient.TdsParser.TryRun(runBehavior runBehavior,SqlCommand的cmdHandler,SqlDataReader的數據流,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj,布爾& dataReady)
在System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(字符串方法名,布爾異步,的Int32超時, Boolean asyncWrite)
at System.Data.SqlClient.SqlComm andInternalExecuteNonQuery(TaskCompletionSource`1 completion

回答

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()