Invalid operation. The connection is closed - sql-server

We're using EntityFramework in a project that just went live. According to our logs, several users are suffering from "Invalid operation. The connection is closed", it happends about 50 times per day.
Exception looks like:
An error occurred while executing the command definition. See the inner exception for details. at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
at System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at xxxx.SelectResultToPeople(IEnumerable`1 result)
at xxxx.GetResult()
at DynamicModule.ns.Wrapped_IPeopleGetter_a853d13914444ca6ab0e016e035520c5.<People_DelegateImplementation>__0(IMethodInvocation inputs, GetNextInterceptionBehaviorDelegate getNext)
Invalid operation. The connection is closed. at System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()
at System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket()
at System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()
at System.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value)
at System.Data.SqlClient.TdsParserStateObject.TryPeekByte(Byte& value)
at System.Data.SqlClient.SqlDataReader.TrySetMetaData(_SqlMetaDataSet metaData, Boolean moreInfo)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryCloseInternal(Boolean closeReader)
at System.Data.SqlClient.SqlDataReader.Close()
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(CommandBehavior behavior)
at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
This exception is thrown on very specific pages, so it's not randomly distributed across the application. One of these pages makes a simple query to the database through Entity framework using a table function. The table function is named "GetPeopleNames" and our ObjectContext class is the one named "SiteEntities".
public class PeopleGetter : IPeopleGetter
{
public List<object> GetResult()
{
using (var siteEntities = new SiteEntities())
{
IQueryable<someResultEntity> result =
siteEntities.GetPeopleNames()
.SortBy("Name", "asc")
.Skip(20*query.CurrentPagingPosition)
.Take(20);
List<People> people = SelectResultToPeople(result)
return people;
}
}
private List<People> SelectResultToPeople(IQueryable<someResultEntity> result)
{
return result
.ToList()
.Select(x => new People { })
.ToList();
}
}
I can't see why it should have something to do with our fault, but i'd better mention that PeopleGetter class is resolved and created by Unity IoC container. The PeopleGetter is registered with a 'PerRquest' LifeTimeManager like this:
public class PerCallContextLifeTimeManager : HierarchicalLifetimeManager
{
private readonly string _key = string.Format("PerCallContextOrRequestLifeTimeManager_{0}", Guid.NewGuid());
public override object GetValue()
{
if (HttpContext.Current != null)
return GetFromHttpContext();
else
return base.GetValue();
}
private object GetFromHttpContext()
{
return HttpContext.Current.Items[_key];
}
public override void SetValue(object newValue)
{
if (HttpContext.Current != null)
SetInHttpContext(newValue);
else
base.SetValue(newValue);
}
private void SetInHttpContext(object newValue)
{
HttpContext.Current.Items.Add(_key, newValue);
}
public override void RemoveValue()
{
}
}
Any ideas why we're getting closed connections?
Thanks for you help!

Related

SQL Server stuck one table during transaction are being request

I have one issue at my work. It about SQL Server stuck one table during has many many transaction request from branches. My solution everyday is cannot do anything without restart SQL Server service.
Below is error log:
E60D17110910021661V1.9.8.3 - 2017-11-09 10:16 : Error: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.\ Details: 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.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()
at System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket()
at System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()
at System.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value)
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, SqlDataReader ds)
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.ExecuteReader()
at TCAM_SOLUTION.Forms.General.CustomerNew.RepositoryBase.ExecuteReader(SqlCommand cmd)
at TCAM_SOLUTION.Forms.Service.SaleOrdering.ServiceInvoices.ServiceInvoiceRepository.GetExistedRepairOrderDetails(List`1 repairOrderDetailIds)
at TCAM_SOLUTION.Forms.Service.SaleOrdering.ServiceInvoices.ServiceInvoiceService.HasItemsSaved(ServiceInvoice invoice)
at TCAM_SOLUTION.Forms.Service.SaleOrdering.ServiceInvoices.FormServiceInvoice.IsNotValidated()
at TCAM_SOLUTION.Forms.Service.SaleOrdering.ServiceInvoices.FormServiceInvoice.btnSave_Click(Object sender, EventArgs e)
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.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Many thanks in advance.
Suy

Fetch return, error to convert nvarchar to bigint

I'm new in react-native, I try to make a fetch request using GET for a login page. I talk to a WebService. The response is correct when I hardcode login and password but if I use my own variable like: this.state.login I have this following error :
System.Data.SqlClient.SqlException: Erreur de conversion du type de données nvarchar en bigint.
à System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
à System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 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.SqlDataReader.TryConsumeMetaData()
à System.Data.SqlClient.SqlDataReader.get_MetaData()
à System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
à System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
à System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
à System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
à System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
à System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
à System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
à System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
à System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
à System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
à dataClub.DSMembreTableAdapters.TAMembreBureau.GetDataForLogin(String LICI_NUMERO, String LICI_MDP, Nullable1 LOGINADMIN) dans C:\Users\vfelder\Documents\Visual Studio 2015\Projects\ClubOnline\dataClub\DSMembre.Designer.cs:ligne 3869
à ClubOnline.WebServices.AppliMobile.connexion(String p_login, String p_mdp) dans C:\Users\vfelder\Documents\Visual Studio 2015\Projects\ClubOnline\ClubOnline\WebServices\AppliMobile.asmx.cs:ligne 46
This is my constructor and fetch request:
constructor(){
super();
this.state = {
login: '',
password: ''
}
}
userLogin(){
fetch('myWebService?p_login=this.state.login&p_mdp=this.state.password',
{
method: 'GET',
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then(res => console.log(res));
}
And this is my TextInput and Button related to my state:
<TextInput
onChangeText={(text)=>this.setState({login: text})}
placeholder={'Identifiant'}
ref={"login"}
returnKeyType={'next'}
style={styles.input}
value={this.state.login}
/>
<TextInput
editable={true}
onChangeText={(text)=>this.setState({password: text})}
placeholder={"Mot de passe"}
ref={'password'}
secureTextEntry={true}
style={styles.input}
value={this.state.password}
/>
<Button
onPress={this.userLogin.bind(this)}
style={styles.buttonContainer}
title={"Connexion"}>
</Button>
I try to make a post request or directly use XMLHttpRequest but it allawys the same, if I use my own variable, this error is generate. I really don't know what I missed. I hope have been as specific as possible.
You are using this.state.login and this.state.password as string , not the value by putting them in single quotes '
fetch('your_url?p_login=this.state.login&p_mdp=this.state.password',
Change this line with one of below:
Use proper single quotes
fetch('your_url?p_login='+this.state.login+'&p_mdp='+this.state.password,
OR : Use New ES6 syntax ${var} :
fetch(`your_url?p_login=${this.state.login}&p_mdp=${this.state.password}`,
Note : I've replaced your url with your_url, so you can easily check the
changes you need to make

NHibernate transactions commit failed

In production I had an episodic timeout exception during commit an Nhibernate transaction. But the records that I expect updated are correct!
In stage environment nothing to report.
Here below the application logs of my batch program.
ERROR 2015-06-25 01:32:01,165 SRV-IIS03 Commit failed
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.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.TdsParser.TdsExecuteTransactionManagerRequest(Byte[] buffer, TransactionManagerRequestType request, String transactionName, TransactionManagerIsolationLevel isoLevel, Int32 timeout, SqlInternalTransaction transaction, TdsParserStateObject stateObj, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransactionYukon(Transacti onRequest transactionRequest, String transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransaction(TransactionReq uest transactionRequest, String name, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalTransaction.Commit()
at System.Data.SqlClient.SqlTransaction.Commit()
at NHibernate.Transaction.AdoTransaction.Commit()
ERROR 2015-06-25 01:32:01,431 SRV-IIS03 Errore imprevisto nel metodo Run:NHibernate.TransactionException: Commit failed with SQL exception ---> System.Data.SqlClient.SqlException: 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.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.TdsParser.TdsExecuteTransactionManagerRequest(Byte[] buffer, TransactionManagerRequestType request, String transactionName, TransactionManagerIsolationLevel isoLevel, Int32 timeout, SqlInternalTransaction transaction, TdsParserStateObject stateObj, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransactionYukon(TransactionRequest transactionRequest, String transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransaction(TransactionRequest transactionRequest, String name, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalTransaction.Commit()
at System.Data.SqlClient.SqlTransaction.Commit()
at NHibernate.Transaction.AdoTransaction.Commit()
--- End of inner exception stack trace ---
at NHibernate.Transaction.AdoTransaction.Commit()
at [omit].Run(String[] args) in [omit].cs:line 153
ERROR 2015-06-25 01:32:01,493 SRV-IIS03 Errore imprevisto nel batch [omit]: NHibernate.TransactionException: Transaction not successfully started
at NHibernate.Transaction.AdoTransaction.CheckBegun()
at NHibernate.Transaction.AdoTransaction.Rollback()
at [omit].RollbackTransazione() in [omit].cs:line 212
at [omit].Run(String[] args) in [omit].cs:line 159
at [omit].Main(String[] args) in [omit].cs:line 29
And here below the structure of my batch
private static ITransaction tx;
public virtual BatchResponseStatus Run(string[] args)
{
var response = BatchResponseStatus.Success;
try
{
//Do some stuff
SetTransaction();
//Collect elements to be processed
foreach (var item in aListOfItem)
{
// Stuff
// Call methods that creates, reads or updates records
// with Fluent Nhibernate or Sql Server Stored procedure
// Write some files
// Zip files
// Update DTO
}
tx.Commit();
}
catch (Exception ex)
{
RollbackTransaction();
XXRepository.NhSession.Clear();
response = BatchResponseStatus.Error;
}
finally
{
DisposeTransaction();
}
return response;
}
private void SetTransaction()
{
tx = XXRepository.NhSession.BeginTransaction(IsolationLevel.ReadUncommitted);
if (tx == null)
throw new Exception("Impossible create a Transaction");
}
private static void RollbackTransaction()
{
if (tx != null)
{
tx.Rollback();
}
}
I use this technologies:
Sql Server stored procedure
Nhibernate 3.4 (Fluent Nhibernate)
.Net Framework 4.5
Anybody can help me?
Thanks.
The timeout occurs on the connection. This means, that the connection times out, but commit continues in Sql Server. As you can see in the log, Rollback fails because the connection is already committed. IMHO, the connection timeout is not properly handled by the SqlClient implementation.
There is a forum thread where this is discussed.

Large dataset comparison timeouts in DbFit

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

Conn.Open() still work after SQL Service is stopped

I have met a issue with sql server 2005 SP2, I have created a windows form and with a button on it, and with the following steps:
Make sure Sql service is running, then click the button, everything is OK
Stop the Sql service, and then click the button again, on my machine, there is not exception at the code of LINE 1, exception occurred at LINE 2, and this is the exception info:
Message: A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace ReconnectSQL
{
public partial class Form1 : Form
{
private string m_ConnectionString = #"Server=(local); Database=testDB; User ID=sa; Password=admins; Connection Timeout=15";
public Form1()
{
InitializeComponent();
}
/// <summary>
///
/// </summary>
public DataTable GetByFillDataTable()
{
try
{
SqlCommand cmd = new SqlCommand("getalldata");
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = this.GetDataTable(cmd);
return dt;
}
catch
{
throw;
}
}
#region common funcs
/// <summary>
///
/// </summary>
/// <param name="cmd"></param>
/// <returns></returns>
private DataTable GetDataTable(SqlCommand cmd)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(this.m_ConnectionString))
{
try
{
conn.Open(); // LINE 1
}
catch (Exception eX)
{
throw;
}
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
try
{
cmd.Connection = conn;
cmd.CommandTimeout = conn.ConnectionTimeout;
adapter.SelectCommand = cmd;
adapter.Fill(dt); // LINE 2
}
catch (Exception eX)
{
throw;
}
}
}
return dt;
}
#endregion
private void button2_Click(object sender, EventArgs e)
{
try
{
DataTable dt = GetByFillDataTable();
listBox1.Items.Add("GetByFillDataTable is called without exceptions!");
}
catch (Exception ex)
{
listBox1.Items.Add(ex.Message);
} }
}
}
Detailed exception info:
- [System.Data.SqlClient.SqlException] {"A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)"} System.Data.SqlClient.SqlException
+ base {"A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)"} System.Data.Common.DbException {System.Data.SqlClient.SqlException}
Class 20 byte
+ Errors {System.Data.SqlClient.SqlErrorCollection} System.Data.SqlClient.SqlErrorCollection
LineNumber 0 int
Number 233 int
Procedure null string
Server "(local)" string
Source ".Net SqlClient Data Provider" string
State 0 byte
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(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParserStateObject.WriteSni()
at System.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode)
at System.Data.SqlClient.TdsParserStateObject.ExecuteFlush()
at System.Data.SqlClient.TdsParser.TdsExecuteRPC(_SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc)
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 ReconnectSQL.Form1.GetDataTable(SqlCommand cmd) in E:\_public_\sqlFail\ReconnectSQL\ReconnectSQL\Form1.cs:line 138
After some investigations, it seems the connection still exist in the connection pool even sql is stopped, so after sql is started and by calling conn.Open() it get the connection object from the pool which should be invalid, then the SqlDataAdapter.Fill cause the exception
http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/99963999-a59b-4614-a1b9-869c6dff921e

Resources