I have a T-SQL and query:
string queryString = @"SELECT AGENT.Number, PERSON.LoginName, AGENT.EnterpriseName FROM Agent AGENT INNER JOIN Person PERSON ON AGENT.PersonID = PERSON.PersonID WHERE LOWER(EnterpriseName) LIKE @entname";
string connStr = null;
try
{
connStr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString + ToInsecureString(Decrypt(ConfigurationManager.AppSettings["admin"])) + ";";
}
catch (Exception ex)
{
Logs.WriteMessage("Error while making connStr " + ex.TargetSite + ex.StackTrace + ex.ToString());
}
try
{
using (SqlConnection connection = new SqlConnection(connStr))
{
connection.Open();
using (SqlCommand command = new SqlCommand(queryString, connection))
{
SqlParameter param = new SqlParameter
{
ParameterName = "@entname",
Value = "'%" + agentName + "%'"
};
command.Parameters.Add(param);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
login = (string)reader[1];
userID = (string)reader[0];
}
}
}
connection.Close();
}
}
And this doesn't work. I get no result, but when I use value in query instead @parameter
I get correct result.
Parameter @entname
doesn't replaced to value so the query failed. Please give me a hint.
When I stop at breakpoint and see the query it looks that:
SELECT AGENT.Number, PERSON.LoginName, AGENT.EnterpriseName
FROM Agent AGENT
INNER JOIN Person PERSON ON AGENT.PersonID = PERSON.PersonID
WHERE LOWER(EnterpriseName) LIKE @entname
So nothing changed.
Parameter @entname doesn't replaced to value so the query failed.
That's not how parameters work. The @entname
parameter marker stays in the query that is sent to SQL Server, along with the matching parameter value.
So with that misunderstanding, you're quoting the parameter value as if it was going to be pasted into the SQL query:
Value = "'%" + agentName + "%'"
which you should not do. Instead do
Value = "%" + agentName + "%"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.