我的连接字符串是静态的,并被多个进程覆盖,但值保持不变。多个进程在不同时间使用上述方法用于不同目的(有时目的可以相同或针对相同的SQL实体)。
我在实时服务器上遇到以下错误(足够强大),但在本地它可以正常工作。实时数据库的大小超过33 GB(并且将逐日增加)。错误是:
无效的操作。连接已关闭。
这是堆栈跟踪:
在System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand命令) 在System.Data.SqlClient.SqlInternalTransaction.Rollback() 在System.Data.SqlClient.SqlTransaction.Rollback() 在WEB.Data.Database.ExecuteCommandToScalar(SqlCommand命令,IEnumerable
1 parameters, IsolationLevel isolationLevel) at WEB.Data.Database.ExecuteStoredProcedureToScalar(SqlCommand command, IEnumerable
1个参数,IsolationLevel isolationLevel) 在WEB.Data.Database.ExecuteStoredProcedureToScalar(String procedureName,IEnumerable1 parameters, IsolationLevel isolationLevel) at Web.SchedulerLibrary.Service.DbService.ExecuteSpToScalar(String spName, List
1个参数) at Web.SchedulerLibrary.Service.DbService.GetLastProceessedOnProduct(Int64 locationId,String prodName,String merchantName) at Web.SchedulerLibrary.SchedulerLibrary.ExecuteForProduct(Int64 merchantId,Int64 locationId,String merchantName,String prodName,String ipAddress)
我的代码是:
public static object ExecuteCommandToScalar(string commandText, IEnumerable<SqlParameter> parameters = null, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, bool? isStoredProcedure = false)
{
SqlCommand command = new SqlCommand(commandText);
if (command == null)
return null;
if (isStoredProcedure == true)
{
command.CommandType = CommandType.StoredProcedure;
}
command.LoadParameters(parameters);
using (var connection = new SqlConnection(Settings.ConnectionString))
{
try
{
connection.Open();
var transaction = connection.BeginTransaction(isolationLevel);
try
{
command.Connection = connection;
command.Transaction = transaction;
var scalar = command.ExecuteScalar();
transaction.Commit();
return scalar;
}
catch
{
transaction.Rollback();
throw;
}
}
finally
{
connection.Close();
}
}
}
以下是导致错误的存储过程。在此存储过程中,我尝试在上次激活产品时获取最后CreatedOn
。此存储过程调用循环(大多数时间循环大约超过500计数)。有时它运行良好,有时会出现此错误。
BEGIN
DECLARE @CreatedOn NVARCHAR(MAX) = ''
;WITH x AS
(
SELECT
*, rn = ROW_NUMBER() OVER (ORDER BY CreatedOn)
FROM
ProductDetails
WHERE
UserID = @UserId
)
SELECT TOP 1 @CreatedOn = CreatedOn
FROM
(SELECT TOP 999999999999999999
ROW_NUMBER() OVER (PARTITION BY CONVERT(DATE, CreatedOn , 103)
ORDER BY CreatedOn DESC) AS RId,
CreatedOn
FROM
(SELECT
(CASE
WHEN (x.IsActive = 1)
THEN CAST(x.CreatedOn AS VARCHAR)
ELSE ''
END) AS CreatedOn
FROM
x
LEFT OUTER JOIN
x AS y ON x.rn = y.rn + 1
AND x.IsActive <> y.IsActive
WHERE
y.IsActive IS NOT NULL
UNION
SELECT TOP 1
pri.CreatedOn
FROM
ProductDetails pri
WHERE
UserID = @UserId
ORDER BY
CreatedOn ASC) A
ORDER BY
CreatedOn DESC) B
SELECT @CreatedOn
END
我不明白哪里有问题?在代码或存储过程中,它是self.Cause同一个调用中的其他存储过程执行完全没有任何问题。我花了几天时间但没有找到问题。
谢谢:)