人生是一场不能存盘的RPG,我只能尽量多搞几个Screenshot

July 8, 2006

SqlCommand Parameter And “Like” 条件

Filed under: SQL&DB Accessing

SqlCommand Parameter And "Like" 条件

为了生成这样一个条SQL语句
SqlCommand cmd = new SqlCommand("SELECT * FROM People WHERE MENU LIKE ‘%包子%’");

我使用了如下的代码:
SqlCommand cmd = new SqlCommand("SELECT * FROM People WHERE MENU LIKE %@Name%");
cmd.Parameters.Add("@Name", SqlDbType.NVarChar);
cmd.Parameters["@Name"].Value = "包子";
执行时报错.

进而改为
SqlCommand cmd = new SqlCommand("SELECT * FROM People WHERE MENU LIKE ‘%@Name%’");
cmd.Parameters.Add("@Name", SqlDbType.NVarChar);
cmd.Parameters["@Name"].Value = "包子";
可执行.
改成
SqlCommand cmd = new SqlCommand("SELECT * FROM People WHERE MENU LIKE ‘%’ + @Name + ‘%’");
也可以干活,从而可以看出MS的做法是在字符类型的@Name参数前后加单引号,而不管%

但我实在不想在代码中出现单引号这种讨厌的东西.
后改为:
SqlCommand cmd = new SqlCommand("SELECT * FROM People WHERE MENU LIKE @Name");
cmd.Parameters.Add("@Name", SqlDbType.NVarChar);
cmd.Parameters["@Name"].Value = "%包子%";

Comments »

The URI to TrackBack this entry is: http://recordsome.blogsome.com/2006/07/08/p124/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.






















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham