Must be aware of the SQL authoring techniques. Multi-conditional query does not stitch the string • The notation

Source: Internet
Author: User

In the project, we often encounter complex query methods, according to the user's input, to determine whether a parameter is legitimate, the legitimate words can be used as a filter, we usually do is to query SQL assigned to a string variable, and then according to the condition of the dynamic stitching where conditions to query. Here's a brief look at the problems and workarounds that are encountered in writing SQL.

an indeterminate field name, and the resulting SQL string concatenation

For example, there is a company to make a system, to support multiple languages, this time we need to store voice information in the database. Then, the corresponding language field is displayed according to the customer's selection query. Let's simulate this scenario, open SQL Server, create a new syslanguage table, add some language fields, such as English,chinese,french, where French doesn't know what it is, it's set to empty.

To build a table of SQL and insert some simple data, SQL is as follows:

CREATE TABLE syslanguage (    Id INT PRIMARY KEY,    中文版 NVARCHAR (),    Chinese NVARCHAR (+),    French NVARCHAR (+)) insert into syslanguage values (1, ' hello ', ' hello ', ' Empty ') insert into syslanguage values (2, ' worlds ', ' World ', ' Empty ') insert into syslanguage values (3, ' book ', ' Books ', ' empty ') insert into syslanguage values (4, ' open ', ' on ', ' empty ') I Nsert into Syslanguage values (5, ' save ', ' saving ', ' empty ') INSERT into syslanguage values (6, ' new ', ' new ', ' empty ')

So, with system performance in mind, we may use stored procedures to reduce network traffic and improve response times. So, in the stored procedure, we pass in a parameter, and then query the specified language field based on the parameter, so how does SQL write?

This time, we will think in C # code, we are all to put SQL into good, and then passed to SQL Server execution, we can stitch the string ah, and then have the following wording:

DECLARE @sql NVARCHAR (+);D eclare @para NVARCHAR (20); SET @para = ' Chinese '; SET @sql = ' Select ID, ' + @para + ' from syslanguage ' Print @sqlexec (@sql)

Of course there is no problem with this writing, but when SQL is complicated, a lot of quotes and character escapes, as well as the lack of space in the concatenation of strings, can be a crash! The following is a non-stitching string, the code is as follows:

DECLARE @para NVARCHAR (20); SET @para = ' Chinese '; SELECT ID, Case @para when ' 中文版 ' then Englishwhen ' Chinese ' then Chinese elsefrenchendas [language]fromsyslanguage

Here uses the case when statement to judge, when the judgment condition too much, writes is also very tired, we may write a function to carry on the encapsulation, certainly, the concrete use that method, depends on the concrete situation.

When you say case, you have to mention another query. First look at the needs: the number of boys from the student table, the number of girls and the total number of students.

Seeing this, we first thought of the SUM function, but then what? Seems like something's wrong. So, what to write, of course, when you use case, look at the code

SELECT SUM (case stusex if 1 then 1 else 0 end) as boys,sum (case stusex when 1 then 0 ELSE 1 END) as Girls,  SUM (stuid ) as Totalfrom Student

See the code, feeling is not very simple ah, was not thought, hehe!

second, the indefinite query condition produces the SQL string concatenation

Accustomed to C # code, suddenly write SQL, feeling still a bit so uncomfortable! Let's take a look at how SQL writes when there are multiple query conditions, but you're not sure how many query conditions you have. We often encounter this demand, many of the controls on the page, to be based on the user's input query, this time we have to determine whether the value of the incoming control to meet the specified conditions, meet the criteria to be used as a query condition, otherwise ignore this condition.

Concatenation string of the way I believe everyone is often used, here do not write, we are connected to see the cloth splicing SQL how to query!

For example, to query the students of the specified condition, the user may query all, or query the boy, or query the student with the specified ID, or ... Wait, there may be many kinds of situations. Let's write a string of SQL, the code is as follows:

DECLARE @ID int;declare @Sex bit;declare @Name NVARCHAR (50); SET @ID =-1; SET @Sex = NULL; SET @Name = ' Ja '; SELECT * from studentwhere (@ID = 1 OR stuid = @ID) and (@Sex are null or stusex = @Sex) and (@Name is null or stuname like '% ' + @Name + '% ')

Here declare three variables, as passed parameters, passed parameters have a default value, or NULL, we add in where to use or add judgment, first Judge @ID =-1, if the condition is established, or will not judge the condition after or, to here (@ID = 1 OR stuid = @ID) Returns a true, equivalent to where true and ..., so it ignores this query condition and continues to follow the filtering judgment below. It's better to write than to stitch a string!

Finally, the role of the n characters in the database, the white is to convert the following string content into Unicode encoding, to write a section of SQL test it

DECLARE @a NVARCHAR () DECLARE @b NVARCHAR () Set @a = N ' Chinese ' set @b = ' Chinese ' IF (@a = @b) PRINT ' value equal ' elseprint ' not Equal '

The output results are as follows:

In the Chinese version of the system, is equal, in the English version of the system, @b will show garbled. We can test it!

Original resources: http://www.cnblogs.com/yunfeifei/p/4079577.html

Must be aware of the SQL authoring techniques. Multi-conditional query does not stitch the string • The notation

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.