C # Normal encounter problems "4"

Source: Internet
Author: User

1. Parametric notation of like in fuzzy query

String keyword= "value"; To blur a matching value

Error Demonstration:  

SQL: string strsql= "select * from [Table] where [Field] like% @Field%";

Parameter: system.data.sqlclient.sqlparameter[] parms = new[] {

New System.Data.SqlClient.SqlParameter ("@Field", system.data.sqldbtype.varchar,400)
};
Parms[0]. Value = KeyWord;

output: the arguments that are output by ADO SQL statement or the literal select * from [Table] where [Field] like% @Field% SQL statement error

Solution (1):

      sql: string strsql= "select * from [Table] where [Field] like '% ' +@Field+ '% ' "

     This way, ADO can input the parameters correctly.

Solution (2):

      sql: string strsql= "select * from [Table] where [Field] like @Field";      

Parameter: system.data.sqlclient.sqlparameter[] parms = new[] {

New System.Data.SqlClient.SqlParameter ("@Field", system.data.sqldbtype.varchar,400)
};
Parms[0]. Value = "%" +keyword +"%";

Analysis:

The like statement that we expect to finally transfer to the database should be: SELECT * FROM [Table] like [Field] like '%value% ' ;

Direct% @Field%, contaminated with ADO parameter marked @ symbol resulting in incorrect substitution of parameters;

Method A string concatenation in the SQL statement to get a value such as '%value% '; Note: The strings in the SQL statement are quoted as the starting character of the string, and the string is stitched in SQL Server with the + sign. so '%value% ' equals '% ' +value '% ',

Method Two add the fuzzy match character directly in the assignment statement;

      

C # Normal encounter problems "4"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.