Attempting to set the column as a parameter in FromRawSql. Query always returns null, I understand this is because the SQL is compiled before parameter values are set. How can I pass the column name into the query as a parameter?
What I'm trying:
var param = new SqlParameter[] {
new SqlParameter("#col", dataDiscriminator),
new SqlParameter("#value", itemDiscValue)
};
var thisq = context.Devices.FromSqlRaw("SELECT * FROM Devices WHERE #col = #value", param);
var thisDevice = thisq.SingleOrDefault();
Will produce the SQL:
DECLARE #col nvarchar(4) = N'Name';
DECLARE #value nvarchar(26) = N'Registration Template';
SELECT * FROM Devices WHERE #prop = #value
you can not use parameter for table or column name. Try this
var param = new SqlParameter[] {
new SqlParameter("#value", itemDiscValue)
};
var thisq = context.Devices.FromSqlRaw($"SELECT * from Devices
WHERE [{dataDiscriminator}] = #value", param).ToList();
var thisDevice = thisq.SingleOrDefault();
I don' t know where dataDiscriminator data from but always remember about the sql script injections.
I am calling a stored procedure which has two params and one of params is out type.
Here is the stored procedure body:
CREATE procedure [dbo].[DetailsANDCount]
(#CustomerID INT = 0,
#Counter int OUT)
AS
IF #CustomerID <= 0
BEGIN
SELECT
Customers.CustomerID, Customers.FirstName,
Customers.LastName, Customers.Address1
FROM
Customers
SELECT #Counter = COUNT(*)
FROM Customers
END
ELSE
BEGIN
SELECT
Customers.CustomerID, Customers.FirstName,
Customers.LastName, Customers.Address1
FROM
Customers
WHERE
Customers.CustomerID = #CustomerID
SELECT #Counter = COUNT(*)
FROM Customers
WHERE Customers.CustomerID = #CustomerID
END
Here is my code which is throwing error:
Additional information: The parameterized query '(#CustomerID
bigint,#Counter int output)DetailsANDCount #Custome' expects the
parameter '#CustomerID', which was not supplied.
Code:
private async void button3_Click(object sender, EventArgs e)
{
using (var db = new TestDBContext1())
{
SqlParameter param1 = new SqlParameter("#CustomerID", 0);
var outParam = new SqlParameter();
outParam.ParameterName = "Counter";
outParam.SqlDbType = SqlDbType.Int;
outParam.Direction = ParameterDirection.Output;
var customers = await db.Database.SqlQuery<Customer>("DetailsANDCount #CustomerID, #Counter OUT", param1, outParam).ToListAsync();
}
}
UPDATE:
using (var db = new TestDBContext1())
{
SqlParameter param1 = new SqlParameter("#CustomerID", 0);
var outParam = new SqlParameter();
outParam.ParameterName = "#Counter";
outParam.SqlDbType = SqlDbType.Int;
outParam.Direction = ParameterDirection.Output;
var customers = await db.Database.SqlQuery<Customer>("DetailsANDCount #CustomerID, #Counter OUT", param1, outParam).ToListAsync();
}
after fixing the 2nd param name still getting the same error.
I have written this function in SQL
alter function TVprest (#emitente int, #mes int, #ano int)
returns float
as
begin
declare #tcu float;
select #tcu = sum(cast(vtprest as money))
from ctrc
where emitente = #emitente and MONTH (EMISSAODATA ) = #mes
and YEAR (EMISSAODATA)=#ano and status = 'A'
if (#tcu is null)
set #tcu = 0;
return #tcu
end
And trying to call the same function in C# with this code:
public double TVprest (int emitente, int mess, int anno)
{
double saida;
SqlConnection abre1 = Tconex.GetConnection();
SqlDataAdapter da3 = new SqlDataAdapter();
if (abre1.State == ConnectionState.Closed) { abre1.Open(); }
SqlParameter emit = new SqlParameter("#emitente", SqlDbType.Int);
emit.Value = emitente;
SqlParameter mes = new SqlParameter("#mes", SqlDbType.Int);
mes.Value = mess;
SqlParameter ano = new SqlParameter("#ano", SqlDbType.Int);
ano.Value = ano;
SqlCommand TotalF = new SqlCommand("SELECT dbo.Tcupom(#emitente,#mes,#ano),", abre1);
TotalF.CommandType = CommandType.Text;
saida = Convert.ToDouble(TotalF.ExecuteScalar());
return saida;
}
When run I get this error :
Failed to convert parameter value from SqlParameter to an Int32
What is wrong? Calling the function with these parameters :
double Tvprest = impx.TVprest(504, 5, 2013);
lblVtprest.Text = Tvprest.ToString();
You haven't added the parameters to your command
SqlCommand TotalF = new SqlCommand("SELECT dbo.Tcupom(#emitente,#mes,#ano),", abre1);
TotalF.Parameters.Add(emit);
TotalF.Parameters.Add(mes);
TotalF.Parameters.Add(ano);
saida = Convert.ToDouble(TotalF.ExecuteScalar());
However, I think you are missing to explain something in your question. You have a function called TVprest but you call a SELECT dbo.Tcupom. Not clear what is that Tcupom
The fundamental error here is, as Steve rightly notes, not adding the parameters correctly. However, as a general code-error-avoidance trick, you might want to try tools like dapper which make it much harder to get it wrong. For example:
return abre1.Query<double>("SELECT dbo.Tcupom(#emitente,#mess,#anno)",
new { emitente, mess, anno }).Single();
That does everything here, but it gets it right, and is easy to read. It even works with your more complex types, i.e.
string region = ...
var customers = connection.Query<Customer>(
"select * from Customers where Region = #region",
new { region }).ToList();
i have a class for my sql duety, and have problem for my
how could i do something like this
SqlParameter storedparam = new SqlParameter();
SqlParameter param1 = new SqlParameter("#userid", SqlDbType.BigInt);
param1.Value = "87";
SqlParameter param2 = new SqlParameter("#ip",SqlDbType.VarChar,40);
param2.Value = "192.168.1.1";
storedparam = param1 + param2; //this parth have problem
Db myobject = new Db(myconection);
myobject.writestoredpro("nameofsotred",storedparam )
In the sql duety, take in params SqlParameter[] like so:
public void WriteStoredProcedure( string Query, params SqlParameter[] SqlParameters ) {
// do it
}
For cases where you're defining a parameter and want to run it in one go, you can also define it like so:
SqlParameter storedParam = new SqlParameter("#ip",SqlDbType.Varchar,40) {
Value = "192.168.1.1"
};
the 'writetostoredpro' method would need to take a collection of SqlParameter objects, and then inside the method, you would need to iterate over the collection adding them to the SqlCommand.Parameters property. Take a look at this link : http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx of how to use the propertied, and SqlCommand class for an idea of what to do: http://msdn.microsoft.com/en-us/library/z4956bkc.aspx
While using the using() {} (sic) blocks as shown below, and assuming that cmd1 does not live beyond the scope of the first using() {} block, why should the second block throw an exception with the message
The SqlParameter is already contained by another SqlParameterCollection
Does it mean that resources and/or handles - including the parameters (SqlParameterCollection) - attached to cmd1 are not released when its destroyed at the end of the block?
using (var conn = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True"))
{
var parameters = new SqlParameter[] { new SqlParameter("#ProductId", SqlDbType.Int ) };
using(var cmd1 = new SqlCommand("SELECT ProductName FROM Products WHERE ProductId = #ProductId"))
{
foreach (var parameter in parameters)
{
cmd1.Parameters.Add(parameter);
}
// cmd1.Parameters.Clear(); // uncomment to save your skin!
}
using (var cmd2 = new SqlCommand("SELECT Review FROM ProductReviews WHERE ProductId = #ProductId"))
{
foreach (var parameter in parameters)
{
cmd2.Parameters.Add(parameter);
}
}
}
NOTE: Doing cmd1.Parameters.Clear() just before the last brace of the first using() {} block will save you from the exception (and possible embarrassment).
If you need to reproduce you can use the following scripts to create the objects:
CREATE TABLE Products
(
ProductId int IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
ProductName nvarchar(32) NOT NULL
)
GO
CREATE TABLE ProductReviews
(
ReviewId int IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
ProductId int NOT NULL,
Review nvarchar(128) NOT NULL
)
GO
I suspect that SqlParameter "knows" which command it's part of, and that that information isn't cleared when the command is disposed, but is cleared when you call command.Parameters.Clear().
Personally I think I'd avoid reusing the objects in the first place, but it's up to you :)
Adding cmd.Parameters.Clear(); after execution should be fine.
Using blocks do not ensure that an object is "destroyed", simply that the Dispose() method is called. What that actually does is up to the specific implementation and in this case it clearly does not empty the collection. The idea is to ensure that unmanaged resources that would not be cleaned up by the garbage collector are correctly disposed. As the Parameters collection is not an unmanaged resource it is not entirely suprising it is not cleared by the dispose method.
I faced this particular error because I was using the same SqlParameter objects as part of a SqlParameter collection for calling a procedure multiple times. The reason for this error IMHO is that the SqlParameter objects are associated to a particular SqlParameter Collection and you can't use the same SqlParameter objects to create a new SqlParameter collection.
So, instead of this:
var param1 = new SqlParameter{ DbType = DbType.String, ParameterName = param1,Direction = ParameterDirection.Input , Value = "" };
var param2 = new SqlParameter{ DbType = DbType.Int64, ParameterName = param2, Direction = ParameterDirection.Input , Value = 100};
SqlParameter[] sqlParameter1 = new[] { param1, param2 };
ExecuteProc(sp_name, sqlParameter1);
/*ERROR :
SqlParameter[] sqlParameter2 = new[] { param1, param2 };
ExecuteProc(sp_name, sqlParameter2);
*/
Do this:
var param3 = new SqlParameter{ DbType = DbType.String, ParameterName = param1, Direction = ParameterDirection.Input , Value = param1.Value };
var param4 = new SqlParameter{ DbType = DbType.Int64, ParameterName = param2, Direction = ParameterDirection.Input , Value = param2.Value};
SqlParameter[] sqlParameter3 = new[] { param3, param4 };
ExecuteProc(sp_name, sqlParameter3);
using defines a scope, and does the automatic call of Dispose() for which we love it.
A reference falling out of scope will not make the object itself "disappear" if another object has a reference to it, which in this case will be the case for parameters having a reference to cmd1.
I have Also got the same issue Thanks #Jon, based on that I gave example.
When I called the below function in which 2 times same sqlparameter passed. In the first database call, it was called properly, but in the second time, it was give the above error.
public Claim GetClaim(long ClaimId)
{
string command = "SELECT * FROM tblClaim "
+ " WHERE RecordStatus = 1 and ClaimId = #ClaimId and ClientId =#ClientId";
List<SqlParameter> objLSP_Proc = new List<SqlParameter>(){
new SqlParameter("#ClientId", SessionModel.ClientId),
new SqlParameter("#ClaimId", ClaimId)
};
DataTable dt = GetDataTable(command, objLSP_Proc);
if (dt.Rows.Count == 0)
{
return null;
}
List<Claim> list = TableToList(dt);
command = "SELECT * FROM tblClaimAttachment WHERE RecordStatus = 1 and ClaimId = #ClaimId and ClientId =#ClientId";
DataTable dt = GetDataTable(command, objLSP_Proc); //gives error here, after add `sqlComm.Parameters.Clear();` in GetDataTable (below) function, the error resolved.
retClaim.Attachments = new ClaimAttachs().SelectMany(command, objLSP_Proc);
return retClaim;
}
This is the common DAL function
public DataTable GetDataTable(string strSql, List<SqlParameter> parameters)
{
DataTable dt = new DataTable();
try
{
using (SqlConnection connection = this.GetConnection())
{
SqlCommand sqlComm = new SqlCommand(strSql, connection);
if (parameters != null && parameters.Count > 0)
{
sqlComm.Parameters.AddRange(parameters.ToArray());
}
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = sqlComm;
da.Fill(dt);
}
sqlComm.Parameters.Clear(); //this added and error resolved
}
}
catch (Exception ex)
{
throw;
}
return dt;
}
I encountered this exception because I had failed to instantiate a parameter object. I thought it was complaining about two procedures having parameters with the same name. It was complaining about the same parameter being added twice.
Dim aParm As New SqlParameter()
aParm.ParameterName = "NAR_ID" : aParm.Value = hfCurrentNAR_ID.Value
m_daNetworkAccess.UpdateCommand.Parameters.Add(aParm)
aParm = New SqlParameter
Dim tbxDriveFile As TextBox = gvNetworkFileAccess.Rows(index).FindControl("tbxDriveFolderFile")
aParm.ParameterName = "DriveFolderFile" : aParm.Value = tbxDriveFile.Text
m_daNetworkAccess.UpdateCommand.Parameters.Add(aParm)
**aParm = New SqlParameter()** <--This line was missing.
Dim aDDL As DropDownList = gvNetworkFileAccess.Rows(index).FindControl("ddlFileAccess")
aParm.ParameterName = "AccessGranted" : aParm.Value = aDDL.Text
**m_daNetworkAccess.UpdateCommand.Parameters.Add(aParm)** <-- The error occurred here.
Issue
I was executing a SQL Server stored procedure from C# when I encountered this issue:
Exception message [The SqlParameter is already contained by another SqlParameterCollection.]
Cause
I was passing 3 parameters to my stored procedure. I added the
param = command.CreateParameter();
only once altogether. I should have added this line for each parameter, it means 3 times altogether.
DbCommand command = CreateCommand(ct.SourceServer, ct.SourceInstance, ct.SourceDatabase);
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "[ETL].[pGenerateScriptToCreateIndex]";
DbParameter param = command.CreateParameter();
param.ParameterName = "#IndexTypeID";
param.DbType = DbType.Int16;
param.Value = 1;
command.Parameters.Add(param);
param = command.CreateParameter(); --This is the line I was missing
param.ParameterName = "#SchemaName";
param.DbType = DbType.String;
param.Value = ct.SourceSchema;
command.Parameters.Add(param);
param = command.CreateParameter(); --This is the line I was missing
param.ParameterName = "#TableName";
param.DbType = DbType.String;
param.Value = ct.SourceDataObjectName;
command.Parameters.Add(param);
dt = ExecuteSelectCommand(command);
Solution
Adding the following line of code for each parameter
param = command.CreateParameter();
This is how I have done it!
ILease lease = (ILease)_SqlParameterCollection.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.FromMinutes(5);
lease.SponsorshipTimeout = TimeSpan.FromMinutes(2);
lease.RenewOnCallTime = TimeSpan.FromMinutes(2);
lease.Renew(new TimeSpan(0, 5, 0));
}
If you're using EntityFramework
I also had this same exception. In my case, I was calling SQL via a EntityFramework DBContext. The following is my code, and how I fixed it.
Broken Code
string sql = "UserReport #userID, #startDate, #endDate";
var sqlParams = new Object[]
{
new SqlParameter { ParameterName= "#userID", Value = p.UserID, SqlDbType = SqlDbType.Int, IsNullable = true }
,new SqlParameter { ParameterName= "#startDate", Value = p.StartDate, SqlDbType = SqlDbType.DateTime, IsNullable = true }
,new SqlParameter { ParameterName= "#endDate", Value = p.EndDate, SqlDbType = SqlDbType.DateTime, IsNullable = true }
};
IEnumerable<T> rows = ctx.Database.SqlQuery<T>(sql,parameters);
foreach(var row in rows) {
// do something
}
// the following call to .Count() is what triggers the exception
if (rows.Count() == 0) {
// tell user there are no rows
}
Note: the above call to SqlQuery<T>() actually returns a DbRawSqlQuery<T>, which implements IEnumerable
Why does calling .Count() throw the exception?
I haven't fired up SQL Profiler to confirm, but I suspect that .Count() is triggering another call to SQL Server, and internally it is reusing the same SQLCommand object and trying to re-add the duplicate parameters.
Solution / Working Code
I added a counter inside my foreach, so that I could keep a row count without having to call .Count()
int rowCount = 0;
foreach(var row in rows) {
rowCount++
// do something
}
if (rowCount == 0) {
// tell user there are no rows
}
Afterthough
My project is probably using an old version of EF. The newer version may have fixed this internal bug by clearing the parameters, or disposing of the SqlCommand object.
Or maybe, there are explicit instructions that tell developers not to call .Count() after iterating a DbRawSqlQuery, and I'm coding it wrong.