ASP Classic Getting Started tutorial using SQL statements in ASP 1th/2 page _ Database related

Source: Internet
Author: User
Tags html page

MySQL, SQL Server, and msql are excellent SQL tools, but unfortunately you don't need them to create a useful SQL statement in an ASP environment. However, you can take advantage of your knowledge of access and the corresponding access skills, plus our tips and tricks, and believe that you will be able to successfully add SQL to your ASP pages.

1. SELECT statement

In the SQL world, the most fundamental operation is the SELECT statement. Many people will be familiar with the following when using SQL directly under Database Tools:
From whichtable
WHERE criteria

Executing the above statement creates a query that holds its results.

In the ASP page file, you can also use the above general syntax, but the situation is slightly different, ASP programming, the contents of theSELECT statement to be assigned as a string to a variable:
SQL = "Select what from whichtable WHERE criteria"

OK, understand the ASP under the SQL "speak" way, then follow the same pattern, as long as you meet your needs, the traditional SQL query mode and conditional query can be useful.

For example, suppose you have a data table in your database, the name is products, and now you want to take out all the records in the list. Then you write the following code:
SQL = "SELECT * FROM Products"

The function of the above code--SQL statement is to take out all the data in the table--after execution, all the records in the datasheet will be selected. However, if you only want to remove a specific column from the table, such as p_name. Then you can't use the * wildcard character, you have to type the name of a specific column, the code is as follows:
SQL = "Select P_name from Products"

After executing the above query, the contents of the Products table and thep_name column will be all selected.

2. Set query conditions with WHERE clause

Sometimes taking out all of the database records may be exactly what you want, but in most cases we usually just have to get some records. So how do you design the query? Of course it will be a bit more brain, and this article also deliberately do not want to let you use that what them recordset.

For example, if you're just going to take outP_nameRecords, and the names of these records must be in lettersWThe head, then you need to use the followingWHEREClause:
SQL = "Select P_name from the products WHERE p_name like ' w% '"

WHEREAfter the keyword is used to filter the data conditions, with these conditions to help, only meet a certain standard of data will be queried. In the above example, the result of the query will only be given a nameWThe head.P_nameRecording.

In the above example, the percent sign (%) means that the query returns allWThe letter starts with a record entry that is followed by any data or even no data. So, at the time of executing the above query, WestAndWillowWill be from ProductsThe table is selected and stored in the query.

As you can see, as long as you carefully designSELECTstatement, you can limit the amount of information that is returned in the recordset, and you will always be able to satisfy your requirements.

These are just the beginning of mastering the SQL use. To help you gradually grasp the complexSELECTStatement usage, let's take a look at some of the key standard terms: comparison operators, all of which you are building your ownSELECTString to get the specific data that you want to use frequently.

WHERE clause basics

At the start of creatingWHEREclause, the simplest way is to use the standard comparison notation, which is <, <=, >, >=, <>, and =. Obviously, you will soon be able to understand the meaning of the following code and the specific results of the operation:
SELECT * FROM Products WHERE P_price >= 199.95
SELECT * FROM Products WHERE P_price <> 19.95
SELECT * from the products WHERE p_version = ' 4 '

Note:Here you will notice that the number 4 in the last example is surrounded by single quotes. The reason is this, in the case of the' 4 'is a literal type, not a numeric type. Because you're going toSELECTStatement into quotation marks to assign it as a value to the variable, so you can also use quotes in the statement.

Comparison operators
The comparison operator specifies the range of content from which the data is fetched. You can use them to create filters to narrow the recordset so that it saves only the information you care about under a given task.

3. Like, not and BETWEEN

You've seen the use of like in the example above where you 've taken the W -heading record. The like decision Word is a very useful symbol. However, in many cases it may give you too much data, so it's a good idea to think about what data you want to get before you use it. Suppose you want to take out a 5-digit SKU number, and it starts with 1 at the end of 5, you can use the caret (_) instead of the% symbol:
SQL = "SELECT * WHERE p_sku like ' 1___5 '"

The following stroke denotes any one character. So in the case of the input "1 _ _ _ 5", your search will be limited to the 5-digit range that meets the specific pattern.

If you want to do the opposite, find all SKU entries that do not match the "1_ _ 5" mode. Then you just need to add not to the like in the example in the statement just now.

If you want to take out a range of data, and you know the starting and ending points of the range, then you might as well use a BETWEEN judgment Word. Now let's assume that you want to select a record within a given table that ranges between 1 and 10. You can use BETWEENas follows:
... WHERE ID BETWEEN 1 and 10

Or you can use the already familiar mathematical judgment words:
... WHERE ID >= 1 and ID >= 10

4. Joint statements

The SQL statements we've talked about so far are relatively simple, and if you can go through a standard recordset loop query, these statements can also meet some more complex requirements. But why do we have to stick to the basic standards of taste? You can add additional symbols, such as and, or , and not to accomplish more powerful functions.

Take the following SQL statement as an example:
SQL = "Select C_firstname, C_lastname, c_email from customers WHERE C_email is
Not NULL and c_purchase = ' 1 ' OR c_purchase = ' 2 ' and c_lastname like
' a% '.

As for your current knowledge of SQL, the above examples are not difficult to explain, but the above statement does not make it very clear to see how the conditional words are glued to a single SQL statement.

Multi-line statement
When the SQL statement is not understood, you might as well break the whole statement into multiple lines of code, and then incrementally add the parts of the query statement to the same variable based on the existing variables:
SQL = "Select C_firstname, C_lastname, c_emailaddress, C_phone"
sql = SQL & "from customers"
sql = SQL & "WHERE c_firstname like ' a% ' and c_emailaddress not NULL"
sql = SQL & "ORDER by C_lastname, C_firstname"
In the last sentence, the SQL variable contains the following complete SELECT statement:
"Select C_firstname, C_lastname, C_emailaddress, C_phone from Customers
WHERE c_firstname like ' a% ' and c_emailaddress NO NULL order by C_lastname,
C_firstname "

The whole sentence according to the decomposition after the obvious good read much! When you are debugging, you may be more willing to knock a few more characters to change the program to read better. Keep in mind, however, that you need to add more space before closing the quotes or after opening the quotes so that you don't get a few words together when the strings are connected.

5. Commencement of implementation

After learning the structure and purpose of the SELECT statement, you should learn how to use it. Under the database tools you have, this may mean that you have to press a button that says "execute." On an ASP Web page, you can execute an SQL statement immediately or as a stored procedure call.

Once you have created the SQL statement, you must also try to access its query results. Obviously, the key here is the ASP recordset. When working with a non-SQL Recordset, the code that creates the recordset is usually as follows:
Dim objrec
Set objrec = Server.CreateObject ("ADODB. Recordset ")" Customers ", objconn, 0, 1, 2

If you are familiar with the above code for ASP is not unfamiliar to you, you should know that "customers" means you open a database in the name of a datasheet.

Open recordset
to make the most of your familiar SQL skills, you need to adjust the most commonly used recordset on a regular ASP page:
 dim objrec
Set Objrec = Server.CreateObject ("ADODB.") Recordset ") sql, objconn, 0, 1, 2

The only modification here is the , and then replace the name of the data table you want to query with a variable containing the SQL statement. One of the advantages of this method

is that you can specify the cursor type (as shown in 0, 1, 2 above).

Execute SQL
You can use a compact line of code to execute SQL statements to create a recordset. The following is syntax:
Dim objrec
Set objrec = objConn.Execute (sql)

In the previous example, the SQL you see is a variable that holds your own SQL SELECT statement. The line "runs" the SQL statement (or queries the database), selects the data and stores the data in the recordset, in the case of the variable Objrec . The main disadvantage of this approach is that you can't choose the type of cursor you want to use. Instead, the recordset is always opened with a forward cursor.

Because of the cursor, you might want to familiarize yourself with two methods of creating a recordset. Executing a query directly saves the time it takes to type a character, but in that case you have to use the default cursor, which is likely to encounter problems that are often not functioning properly. Whichever way you use it, the biggest difference between the two is nothing more than code refinement. Without considering what fields you get, what your criteria are, and how you store the data, the SQL Recordset will be much smaller in volume than the standard recordset opened on the ASP, let alone the simplicity of the operation. After all, by filtering the data, you eliminate time-consuming if-then tests and possible loops.

Writing tests with SQL
Here's a tip that many professional ASP programmers are accustomed to "write" their own SQL statements when testing a Web page. Doing so can help you debug your code, because you can see the string passed to the server for execution. And all you have to do is add Response.Writeyourvariable to display the information on the screen. You should attach this information when you submit an SQL-related issue to an ASP discussion group.

6. Store the query

When your query is relatively simple, it doesn't take much time to create SQL statements from scratch, but complex queries are different, and there are many development errors from scratch each time. So, once you have SQL running smoothly, you'd better save them and call them when you need them. In this way, even a simple query you can always use the stored query statement.

Let's say you have a weekly report to the team, pointing out the current business support issues that need to be selected from your database, and to select records by date, and sort by the category of support issues that your team uses. Once you have designed this query, why should you rewrite it every week? Instead of creating a query on your HTML page, you should create a query with your database tools and save it.

You can then insert the query into your ASP page using the ActiveCommand attribute. The first one or two of the time you might think it's no fun, but it's just a few lines of code:
Set objsq = Server.CreateObject ("Adodb.command")
Objsq.activeconnection = "DatabaseName"

Objsq.commandtext = "Storedqueryname"
Objsq.commandtype = adCmdStoredProc

Set Objrec = Objsq.execute

Note that using adCmdStoredProc means that you have included files on the page. This file defines the access constants that you can access by name rather than by number. Just include the file on the page (<!--#INCLUDE-->), and then you can use adCmdStoredProc names. This will make it easier to understand what the above stored query means in the future when you see it.

Current 1/2 page 12 Next read the full text
Related Article

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: 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.