Wednesday, January 27, 2010

Parameters.AddWithValue method in SQL statement Where the usage of the words

It was questioned, Parameters.AddWithValue method in some cases so bad that he's written like this:

string strWhere = "'%good%'";
strSql = "SELECT * FROM area Where [name] like @strWhere";//it is no use
cmd.Parameters.AddWithValue("@strWhere", strWhere);

This is because, ASP.NET generated SQL statements and will be followed by the Like a single quotation mark, causing the error, if you open the SQL Server track manager, you can see the implementation of the statement is as follows:

exec sp_executesql N'SELECT * FROM Article Where [Title] like @strWhere',N'@strWhere nvarchar(5)',@strWhere=N'%why%'

Not difficult to understand, in the OldDbCommand will be similar in approach. The correct code is:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>

No comments:

Post a Comment