Related
I am using VS Studio 2105 / SSMS 2014 v 12.0.410. Using VB.net.
I am running a console app that does polling on the 0 and 30 second mark. It will do this 24 by 7. As part of the process, a background thread is spawned. (See explanation below).
The database connection string is:
add key="ConnectionString" value="Server=xxxxx,14334;Database=xxx_dev;Uid=xxx_dev;Password=xxxxxx;MultipleActiveResultSets=true"
The class and its functions called for open and close:
Dim strConnectionString As String = ConfigurationManager.AppSettings("ConnectionString")
Sub OpenDB()
If objConn.State = Data.ConnectionState.Open Then
objConn.Close()
End If
objConn.ConnectionString = strConnectionString
objConn.Open()
objCmd.Connection = objConn
objCmd.CommandType = Data.CommandType.Text
End Sub
Sub CloseDB()
objConn.Close()
End Sub
I customized the error message to get all that I could about it.
A severe error occurred on the current command. The results, if any, should be discarded. --> State: 0 --> Source: .Net SqlClient Data Provider --> Error number: 0 --> Line number: 0 --> Line number: -2146232060 --> Class: 11 --> Procedure: --> Call stack: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at ReliableSiteBandwidthPollingTester.Module1.SaveBandwidthPollingLog(Switch SaveSwitch, String& strMessage) in C:\Dans\Work 2\Working Area\Switch Polling - design 3\Tester apps\ReliableSiteBandwidthPollingTester\ReliableSiteBandwidthPollingTester\Module1.vb:line 427
The polling process:
It interrogates a network switch gathering data. After the interrogation, it then executes a simple stored procedure 105 times which inserts a row into a table each time. It then starts a background thread which executes a "calculation process" stored procedure that uses the table just inserted into as well as other tables. It does inserts into another table - and potentially deletes. A transaction is used. It either commits or rolls back. However, I believe that the procedure does not finish before the next poll begins - the next 30 second mark.
The simple insert stored procedure has been tested stand alone many times and works fine every time.
The "calculation process" stored procedure has been tested stand alone many times and works fine every time.
I start the console app and it it polls 3 times and the fails with that error. Before failing, it writes the out 3 sets of 105 rows to the table. It also inserts 290 rows into another table as part of the process.
Sub PollSwitch(sender As Object, e As ElapsedEventArgs)
Dim strMessage As String = ""
Dim strPollError As String = ""
Dim bPollResult As Boolean
Dim NetworkSwitch As Switch
' This is the format to display as it is how it is stored in the info log table.
Dim dtFormat As String = "yyyy-MM-dd hh:mm:ss.fff"
If bErrorInThread = True Then
' There was an error in the background thread during the previous issuance of the thread. So do not continue.
strMessage = "Critical Error - in the background thread. See the 'BandwidthInfoLog' table. Refer to this log date: " + dtThreadStartDateTime.ToString(dtFormat)
End If
If strMessage = "" Then
' Create a new instance.
NetworkSwitch = New Switch(strCommandLineSwitchIP, strCommandLineCommunityString)
Try
' Do the switch polling.
bPollResult = NetworkSwitch.Poll(strPollError)
If bPollResult = False Then
strMessage = "Warning - in bandwidth poll. Poll error at " & Now & ": " & strPollError & " Poll will continue."
Else
' Save to the bandwidth polling log.
SaveBandwidthPollingLog(NetworkSwitch, strMessage)
If InStr(strMessage, "Critical") = 0 Then
Console.WriteLine("Successfully polled at " & Now() & ".")
' Set the date/time as it will be used above in an error message should the thread process fail.
dtThreadStartDateTime = Now()
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Now do the "calculation process" - it will be in it's own background thread.
' Note: the thread ends when the ProcessCalculatedSwitchPolling method ends.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim thread As New Thread(AddressOf ProcessCalculatedSwitchPolling)
thread.Start()
End If
End If
Catch ex As Exception
strMessage = "Critical Error - in bandwidth poll - " & ex.Message & "<br /><br />Switch: " & strCommandLineSwitchIP
End Try
End If
If InStr(strMessage, "Critical") > 0 Then
' Stop this method (this poll timer) as there is a critical error.
DisposeTimer()
' Show message.
Console.WriteLine(strMessage)
Console.WriteLine("--------->>>> PRESS ENTER TO QUIT.")
Console.ReadKey()
' Exit the console application here as there is a critical error.
' Normally the exit would occur in the main method when the User hits a key.
Environment.Exit(0)
End If
End Sub
The call stack shows it fails on line 427 which is the .ExecuteNonQuery() line.
Sub SaveBandwidthPollingLog(ByVal SaveSwitch As Switch, ByRef strMessage As String)
Const strFunctionId As String = "VB - savebandwidthpollinglog. Error ID: "
Const iSQLErrorId As Integer = 501
Const iCATCHErrorId As Integer = 502
Dim dtCurrentDateTime As Date = Now()
Dim strProcessInfoLogResult As String = ""
Dim strAdditionalInfoForLog As String = ""
' This is the format to display as it is how it is stored in the info log table.
Dim dtFormat As String = "yyyy-MM-dd hh:mm:ss.fff"
DBFunc.OpenDB()
Try
With DBFunc.objCmd
.CommandType = Data.CommandType.StoredProcedure
.CommandText = "InsertBandwidthLogTest6"
' Note: it was timing out, so the SqlCommand.CommandTimeout property has expired; the default timeout is 30 seconds.
.CommandTimeout = 0
For Each SavePort In SaveSwitch.Port
.Parameters.Clear()
.Parameters.AddWithValue("#SwitchIP", SaveSwitch.IP)
.Parameters.AddWithValue("#PortIndex", SavePort.Index)
.Parameters.AddWithValue("#PortSpeed", SavePort.Speed)
.Parameters.AddWithValue("#InOctets", SavePort.InOctets)
.Parameters.AddWithValue("#OutOctets", SavePort.OutOctets)
.Parameters.AddWithValue("#TimeStamp", SavePort.TimeStamp)
.ExecuteNonQuery()
Next
End With
Catch sqlex As SqlException
' Its a critical issue.
If InStr(sqlex.Message, "Critical") > 0 Then
' Coming from the stored procedure.
strMessage = sqlex.Message
Else
strProcessInfoLogResult = ProcessInfoLog(dtCurrentDateTime, sqlex.Message + " --> State: " + sqlex.State.ToString() + " --> Source: " + sqlex.Source + " --> Error number: " + sqlex.Number.ToString() + " --> Line number: " + sqlex.LineNumber.ToString() + " --> Line number: " + sqlex.HResult.ToString() + " --> Class: " + sqlex.Class.ToString() + " --> Procedure: " + sqlex.Procedure + " --> Call stack: " + sqlex.StackTrace, strAdditionalInfoForLog, strFunctionId, iSQLErrorId)
End If
Catch ex As Exception
strProcessInfoLogResult = ProcessInfoLog(dtCurrentDateTime, ex.Message, strAdditionalInfoForLog, strFunctionId, iCATCHErrorId)
Finally
' Close database.
DBFunc.CloseDB()
End Try
End Sub
The Thread process:
Public Sub ProcessCalculatedSwitchPolling()
Const strFunctionId As String = "VB - processcalculatedswitchpolling. Error ID: "
Const iSQLErrorId As Integer = 601
Const iCATCHErrorId As Integer = 602
Dim strProcessInfoLogResult As String = ""
Dim strAdditionalInfoForLog As String = ""
Dim strInputParms As String = ""
' Set for the error log.
strInputParms = "S/P parmameters - switch IP Address: " & strCommandLineSwitchIP
DBFunc.OpenDB()
Try
With DBFunc.objCmd
.CommandType = Data.CommandType.StoredProcedure
.CommandText = "ProcessBandwidthLogCalculatedTest6"
' Note: it was timing out, so the SqlCommand.CommandTimeout property has expired; the default timeout is 30 seconds.
.CommandTimeout = 0
.Parameters.Clear()
.Parameters.AddWithValue("#SwitchIP", strCommandLineSwitchIP)
.ExecuteNonQuery()
End With
Catch sqlex As SqlException
' Its a critical issue.
If InStr(sqlex.Message, "Critical") > 0 Then
' Coming from the stored procedure.
' Set the global variable - the thread error indicator.
bErrorInThread = True
Else
' Not coming from the stored procedure.
bErrorInThread = True
' Log the exception as it was not logged in the stored procedure.
strAdditionalInfoForLog = strInputParms
strProcessInfoLogResult = ProcessInfoLog(dtThreadStartDateTime, sqlex.Message, strAdditionalInfoForLog, strFunctionId, iSQLErrorId)
End If
Catch ex As Exception
bErrorInThread = True
' Log the exception.
strAdditionalInfoForLog = strInputParms
strProcessInfoLogResult = ProcessInfoLog(dtThreadStartDateTime, ex.Message, strAdditionalInfoForLog, strFunctionId, iCATCHErrorId)
Finally
' Close database.
DBFunc.CloseDB()
End Try
End Sub
I have been trying to debug a piece of code and I have been thus far very unsuccessful in doing this.
I keep on getting this error
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ')'
and I can't seem to see where the error is.
The code is below, having looked at various answers on this site and looked at the examples. The situation is that I am writing a program that accesses a database and is able to add and save data to that database. It is located on a server - though this is on my laptop.
I have written, re-written and copied the connection string to ensure there are no mistakes in it and even dropped a copy of the string into word and compared it to the one that is in the coding itself but to no avail.
public partial class AddingClients : Form
{
public AddingClients()
{
InitializeComponent();
}
String CompanyName2;
String ClientName2;
String CompanyAddress12;
String CompanyAddress22;
String CompanyAddress32;
String CompanyTown2;
String CompanyPostCode2;
String TelephoneNumber2;
String CompanyEMail2;
String CompanyNotes2;
String ClientReference2;
public SqlConnection con;
public void connection()
{
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
}
private void Finish_Click(object sender, EventArgs e)
{
ClientReference2 = Id.Text;
CompanyName2 = CompanyName.Text;
ClientName2 = ClientName.Text;
CompanyAddress12 = CompanyAddress1.Text;
CompanyAddress22 = CompanyAddress2.Text;
CompanyAddress32 = CompanyAddress3.Text;
CompanyTown2 = CompanyTown.Text;
CompanyPostCode2 = CompanyPostCode.Text;
TelephoneNumber2 = TelephoneNumber.Text;
CompanyEMail2 = CompanyEMail.Text;
CompanyNotes2 = CompanyNotes.Text;
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail, CompanyNotes,) VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10, #parameter11,)", con);
cmd.Parameters.AddWithValue("#parameter1", ClientReference2);
cmd.Parameters.AddWithValue("#parameter2", ClientName2);
cmd.Parameters.AddWithValue("#parameter3", CompanyName2);
cmd.Parameters.AddWithValue("#parameter4", CompanyAddress12);
cmd.Parameters.AddWithValue("#parameter5", CompanyAddress22);
cmd.Parameters.AddWithValue("#parameter6", CompanyAddress32);
cmd.Parameters.AddWithValue("#parameter7", CompanyTown2);
cmd.Parameters.AddWithValue("#parameter8", CompanyPostCode2);
cmd.Parameters.AddWithValue("#parameter9", TelephoneNumber2);
cmd.Parameters.AddWithValue("#parameter10", CompanyEMail2);
cmd.Parameters.AddWithValue("#parameter11", CompanyNotes2);
cmd.ExecuteNonQuery();
//this method moves to the next screen.
this.Hide();
Asset M1 = new Asset();
M1.Show();
}
private void SaveandNext_Click(object sender, EventArgs e){
ClientReference2 = Id.Text;
CompanyName2 = CompanyName.Text;
ClientName2 = ClientName.Text;
CompanyAddress12 = CompanyAddress1.Text;
CompanyAddress22 = CompanyAddress2.Text;
CompanyAddress32 = CompanyAddress3.Text;
CompanyTown2 = CompanyTown.Text;
CompanyPostCode2 = CompanyPostCode.Text;
TelephoneNumber2 = TelephoneNumber.Text;
CompanyEMail2 = CompanyEMail.Text;
CompanyNotes2 = CompanyNotes.Text;
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail, CompanyNotes,) VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10, #parameter11,)", con);
cmd.Parameters.AddWithValue("#parameter1", ClientReference2);
cmd.Parameters.AddWithValue("#parameter2", ClientName2);
cmd.Parameters.AddWithValue("#parameter3", CompanyName2);
cmd.Parameters.AddWithValue("#parameter4", CompanyAddress12);
cmd.Parameters.AddWithValue("#parameter5", CompanyAddress22);
cmd.Parameters.AddWithValue("#parameter6", CompanyAddress32);
cmd.Parameters.AddWithValue("#parameter7", CompanyTown2);
cmd.Parameters.AddWithValue("#parameter8", CompanyPostCode2);
cmd.Parameters.AddWithValue("#parameter9", TelephoneNumber2);
cmd.Parameters.AddWithValue("#parameter10", CompanyEMail2);
cmd.Parameters.AddWithValue("#parameter11", CompanyNotes2);
cmd.ExecuteNonQuery();
this.Hide();
AddingClients M1 = new AddingClients();
M1.Show();//Saves the current data then goes to the next record to be tested.
You have an extra comma before the closing ) in your column list and VALUES sections:
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail,
CompanyNotes,)
****
VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10,
#parameter11,)", con);
****
Remove that and you should be fine
Query is sum up the top 500 account balances grouped by currencies, used in comparison query from a new SQL 2012 server and existing server to validate no changes in the new 2012 server.
Set timeout property to |set option|command|900| and to no avail.
Below is extract of the error:
System.Data.SqlClient.SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.SqlClient.SqlConnection.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.SetMetaData(_SqlMetaDataSet metaData, Boolean moreInfo)
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(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet)
at dbfit.DatabaseTest.GetDataTable(Symbols symbols, String query, IDbEnvironment environment, Int32 rsNo)
at dbfit.fixture.StoreQuery.DoTable(Parse table)
at fitSharp.Fit.Operators.InterpretFlow.DoTable(Tree`1 table, Interpreter activeFixture, Boolean inFlow)
I've attempted to reduce the number of rows to check to 300 from 500 and that seems to work, however a large dataset would be ideal to highlight any discrepancies.
I'm also looking into changing the query to something else to either break it up to a smaller resultset or create an alternative
The query is below, if anyone has a better solution to optimise the query:
select
TOP 1000 fab.DateKey,be.BK_ActOId,be.PtId,be.PDesc,
be.OId,be.ODesc,be.SubOId,be.SubODesc,
rc.Currency,SUM(CASE WHEN rc.Currency = '_NA' THEN FAB.Balance ELSE 0 END) as bal_OrigCcy
,SUM(CASE WHEN rc.Currency = 'AUD' THEN FAB.Balance ELSE 0 END) as bal_AUD
,SUM(CASE WHEN rc.Currency = 'GBP' THEN FAB.Balance ELSE 0 END) as bal_GBP
,SUM(CASE WHEN rc.Currency = 'SGD' THEN FAB.Balance ELSE 0 END) as bal_SGD
,SUM(CASE WHEN rc.Currency = 'USD' THEN FAB.Balance ELSE 0 END) as bal_USD
from olap.v_FactAccB fab
inner join OLAP.v_DimCur dc on dc.CurrencyKey = fab.BalanceCurrencyKey
inner join olap.v_DimReportingCur rc on rc.CurrencyKey = fab.ReportingCurrencyKey
inner join OLAP.v_DimBusinessEntity be on be.BusinessEntityKey = fab.BusinessEntityKey
and rc.Currency in ('_NA', 'AUD', 'GBP', 'SGD','USD')
and fab.DateKey = 20130912
and fab.PlatformKey = 1
group by fab.DateKey, be.BK_ActOId, be.PId, be.PDesc
,be.OId, be.ODesc, be.SubOId, be.SubODesc, rc.Currency
order by fab.DateKey, be.BK_ActOId, be.PId, be.PDesc, be.OId, be.ODesc, be.SubOId, be.SubODesc, rc.Curr
Does anyone have alternatives other than the one above
I would rewrite your query to use a PIVOT instead of the repeated SUM(CASE... )
eg:
select * from yourtable
pivot (SUM(balance) for currency in (_NA,AUD,GBP,SGD,USD)) p
I have a stored procedure that does quite a bit of joins. The query though runs pretty fast, around 3 seconds. I just cant figure out the below error poping up every once in a while. I event cache the document that uses this query for a minute so it doesnt get ran over and over. I am using Entity Framework 5, and my stored procedure is using a CTE to do the paging. Any clues or insight?
System.Data.SqlClient.SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
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, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
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.ExecuteReader()
at System.Data.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, MergeOption mergeOption, Object[] parameters)
at System.Data.Objects.ObjectContext.ExecuteStoreQuery[TElement](String commandText, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery[TElement](String sql, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlQueryAsIEnumerable[TElement](String sql, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery(Type elementType, String sql, Object[] parameters)
at System.Data.Entity.Internal.InternalSqlNonSetQuery.GetEnumerator()
at System.Data.Entity.Internal.InternalSqlQuery`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Tournaments.Data.Repositories.Games.GamesRepository.GetGamesPaged(IGamesCriteria criteria)
Entity Framework Method
public PagedResult<GameComplex> GetGamesPaged(IGamesCriteria criteria)
{
var results = DataContext.Database.SqlQuery<GameComplex>("EXEC [Schema].[Database] #Page, #PageSize, #SortOrder, #SortDirection, #EventId, #DivisionId, #DivisionTeamId, #Date, #SearchToken, #MemberId",
new SqlParameter("Page", criteria.Page),
new SqlParameter("PageSize", criteria.PageSize),
new SqlParameter("SortOrder", GetDataValue(criteria.SortOrder)),
new SqlParameter("SortDirection", GetDataValue(criteria.SortDirection)),
new SqlParameter("EventId", GetDataValue(criteria.EventId)),
new SqlParameter("DivisionTeamId", GetDataValue(criteria.DivisionTeamId)),
new SqlParameter("DivisionId", GetDataValue(criteria.DivisionId)),
new SqlParameter("Date", GetDataValue(criteria.Date)),
new SqlParameter("SearchToken", GetDataValue(criteria.SearchToken)),
new SqlParameter("MemberId", GetDataValue(criteria.MemberId))).ToList();
return new PagedResult<GameComplex>
{
Page = criteria.Page,
PageSize = criteria.PageSize,
Total = results.Any(q => q != null) ? results.FirstOrDefault().Total : 0,
Results = results
};
}
SQL Server Stored Procedure Parameter Signature
ALTER PROCEDURE [Schema].[Database]
#Page INT = 1,
#PageSize INT = 10,
#SortOrder NVARCHAR(100) = 'Id',
#SortDirection VARCHAR(4) = 'ASC',
#EventId INT = NULL,
#DivisionId INT = NULL,
#DivisionTeamId INT = NULL,
#Date DATETIME = NULL,
#SearchToken NVARCHAR(100) = NULL,
#MemberId INT = NULL
AS
You may need to adjust the COMMAND timeout.
See:
Set Command Timeout in entity framework 4.3
or
How to set CommandTimeout for DbContext?
EDIT
Command Timeout:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout.aspx
Connection Timeout:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx
EDIT:
Another possible issue is "parameter sniffing".
http://blogs.msdn.com/b/queryoptteam/archive/2006/03/31/565991.aspx
So try one of the parameter sniffing workarounds:
ALTER PROCEDURE [Schema].[Database]
#Page INT = 1,
#PageSize INT = 10,
#SortOrder NVARCHAR(100) = 'Id',
#SortDirection VARCHAR(4) = 'ASC',
#EventId INT = NULL,
#DivisionId INT = NULL,
#DivisionTeamId INT = NULL,
#Date DATETIME = NULL,
#SearchToken NVARCHAR(100) = NULL,
#MemberId INT = NULL
AS
Declare #PageCopyOf int
Select #PageCopyOf = #Page
Declare #PageSizeCopyOf int
Select #PageSizeCopyOf = #PageSize
Declare #SortOrderCopyOf NVARCHAR(100)
Select #SortOrderCopyOf = #SortOrder
Declare #SortDirectionCopyOf VARCHAR(4)
Select #SortDirectionCopyOf = #SortDirection
Declare #EventIdCopyOf int
Select #EventIdCopyOf = #EventId
Declare #DivisionIdCopyOf int
Select #DivisionIdCopyOf = #DivisionId
Declare #DivisionTeamIdCopyOf int
Select #DivisionTeamIdCopyOf = #DivisionTeamId
Declare #DateCopyOf DATETIME
Select #DateCopyOf = #Date
Declare #SearchTokenCopyOf NVARCHAR(100)
Select #SearchTokenCopyOf = #SearchToken
Declare #MemberIdCopyOf int
Select #MemberIdCopyOf = #MemberId
And then everything below this uses/consumes the #XXXXXCopyOf variable and NOT the original variable (name).
It's worth a try.
Just a guess, but the query runs fast (3 seconds) only when it is cached. Otherwise, it takes a lot longer and exceeds your server timeout setting. Since System.Data.SqlClient is raising the exception, it is likely that the default timeout is only 15 seconds.
MSDN: "The default value is 15 seconds"
Alternatively, try the CommandTimeout property of the SQLCommand object, which defaults to 30 seconds.
CommandTimeout
I am using the data reader to show specific column data into grid view. Actually i want to get the last day record from table.
DateTime yestarday = DateTime.Today.AddDays(-1);
string query = "select NAME,CLOSING_READING,RATE from CASHSALE_DETAIL where DATE = '" + yestarday + "'";
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandText = query;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
CashSaleVoucherGridView.Rows.Add(num, "", dr["NAME"].ToString(), dr["CLOSING_READING"].ToString(), "", "", "", dr["RATE"].ToString());
num++;
}
On above given query data reader returns me 0 record.
Any Suggstions????
First check if your select query it its returning records then
add dr.HasRows to check your data reader return rows or not
DateTime yesterday = DateTime.Today.AddDays(-1);
string query = "select NAME,CLOSING_READING,RATE from CASHSALE_DETAIL where DATE = #date";
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#date", yesterday );
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
CashSaleVoucherGridView.Rows.Add(num, "", dr["NAME"].ToString(), dr["CLOSING_READING"].ToString(), "", "", "", dr["RATE"].ToString());
num++;
}
}
else
{
//Throw error ("No rows found.");
}
Best Regards
the issue is on this statement
string query = "select NAME,CLOSING_READING,RATE from CASHSALE_DETAIL where DATE = '" + yestarday + "'";
use parameterized command
DateTime yesterday = DateTime.Today.AddDays(-1);
string query = "select NAME,CLOSING_READING,RATE from CASHSALE_DETAIL where DATEADD(dd, 0, DATEDIFF(dd, 0, DATE )) = DATEADD(dd, 0, DATEDIFF(dd, 0, #yesterday))";
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#yesterday", yesterday);
SqlDataReader dr = cmd.ExecuteReader();
You can format the date field like this
string query = "select NAME,CLOSING_READING,RATE from CASHSALE_DETAIL
where convert(varchar(15),DATE,101)= '" + yestarday + "'";
but the method mentioned by #BizApps and #mdcuesta like below is very less erroneous
cmd.Parameters.AddWithValue("#yesterday", yesterday);