Full Set of SQL operations
The following statements are MSSQL statements and cannot be used in access.
SQL classification:
DDL-Data Definition Language (create, alter, drop, declare)
DML-data manipulation language (select, delete, update, insert)
DCL-Data Control Language (Grant, revoke, commit, rollback)
First, we will briefly introduce the basic statements:
1. Description: Create a database
Create Database database-name
2. Description: delete a database.
Drop database dbname
3. Description: Back up SQL Server
--- Create a device for the backup data
Use master
Exec sp_addumpdevice 'disk', 'testback', 'c:/mssql7backup/mynwind_1.dat'
--- Start backup
Backup database pubs to testback
4. Description: Create a new table.
Create Table tabname (col1 type1 [not null] [primary key], col2 type2 [not null],...)
Create a new table based on an existing table:
A: Create Table tab_new like tab_old (use the old table to create a new table)
B: Create Table tab_new as select col1, col2... From tab_old definition only
5. Description: Delete the new table drop table tabname
6. Description: Add a column.
Alter table tabname add column Col type
Note: Columns cannot be deleted after they are added. After columns are added to DB2, the data type cannot be changed. The only change is to increase the length of the varchar type.
7. Description: Add a primary key: alter table tabname add primary key (COL)
Delete a primary key: alter table tabname drop primary key (COL)
8. Description: Create an index: Create [unique] index idxname on tabname (COL ....)
Delete index: drop index idxname
Note: The index cannot be changed. To change the index, you must delete it and recreate it.
9. Description: Create view viewname as select statement
Delete view: Drop view viewname
10. Description: several simple basic SQL statements
Select: Select * From Table1 where range
Insert: insert into Table1 (field1, field2) values (value1, value2)
Delete: delete from Table1 where range
Update: Update Table1 set field1 = value1 where range
Search: Select * From Table1 where field1 like '% value1 %' --- the like syntax is very subtle, query information!
Sort: Select * From Table1 order by field1, field2 [DESC]
Total: Select count * as totalcount from Table1
Sum: Select sum (field1) as sumvalue from Table1
Average: Select AVG (field1) as avgvalue from Table1
MAX: Select max (field1) as maxvalue from Table1
Min: select Min (field1) as minvalue from Table1
11. Description: several advanced query Operators
A: Union operator
The Union operator combines two other result tables (such as Table1 and table2) and removes any duplicate rows from the table to generate a result table. When all is used together with Union (that is, Union all), duplicate rows are not eliminated. In either case, each row of the derived table is from either Table1 or table2.
B: Random t operator
The distinct t operator derives a result table by including all rows in Table 1 but not in table 2 and eliminating all repeated rows. When all is used with distinct T (distinct t all), duplicate rows are not eliminated.
C: intersect Operator
The Intersect operator derives a result table by only including the rows in Table1 and Table2 and eliminating all repeated rows. When all is used with intersect (intersect all), duplicate rows are not eliminated.
Note: The query results of several computation words must be consistent.
12. Note: use external connections
A. left Outer Join:
Left Outer Join (left join): the result set contains the matched rows in the connected table, and all rows in the left connected table.
SQL: select a. a, a. B, A. C, B. C, B. D, B. F from a left out join B on A. A = B. C
B: Right outer join:
Right Outer Join (right join): the result set includes both matched join rows in the connection table and all rows in the right join table.
C: Full outer join:
Full outer join: includes not only matching rows in the symbolic join table, but also all records in the two join tables.
Next, let's look at some good SQL statements.
1. Description: copy a table (only copy structure, source table name: a new table name: B) (access available)
Method 1: Select * into B from a where 1 <> 1
Method 2: Select top 0 * into B from
2. Description: copy a table (copy data, source table name: A target table name: B) (access available)
Insert into B (a, B, c) Select D, E, F from B;
3. Description: Table Copying across databases (absolute path for specific data) (access is available)
Insert into B (a, B, c) Select D, E, F from B in 'specific database' where Condition
Example:... from B in '"& server. mappath (". ") &"/data. mdb "&" 'where ..
4. Description: subquery (table name 1: Table A name 2: B)
Select a, B, c from a where a in (select D from B) or: select a, B, c from a where a in (1, 2, 3)
5. Description: displays the article, Submitter, and last reply time.
Select a. Title, A. username, B. adddate from Table A, (select max (adddate) adddate from table where table. Title = A. Title) B
6. Description: External join query (table name 1: Table A name 2: B)
Select a. a, a. B, A. C, B. C, B. D, B. F from a left out join B on A. A = B. C
7. Description: Online View query (table name 1:)
Select * from (select a, B, c from a) t where T. A> 1;
8. Description: between usage. When between restricts the Data Query range, it includes the boundary value. Not between does not include
Select * From Table1 where time between time1 and time2
Select a, B, c, from Table1 where a not between value 1 and value 2
9. Description: How to Use in
Select * From Table1 where a [not] In ('value 1', 'value 2', 'value 4', 'value 6 ')
10. Description: two associated tables are used to delete information that is not in the secondary table.
Delete from Table1 where not exists (select * From Table2 where table1.field1 = table2.field1)
11. Notes: four table join query problems:
Select * from a left inner join B on. A = B. B right inner join C on. A = C. C inner join D on. A = D. d Where .....
12. Note: Five minutes ahead of schedule reminder
SQL: Select * from Schedule where datediff ('minute ', F Start Time, getdate ()> 5
13. Note: One SQL statement is used to handle database paging.
Select top 10 B. * From (select top 20 primary key field, sorting field from table name order by sorting field DESC) A, table name B where B. primary key field =. primary key field order by. sorting Field
14. Note: The first 10 records
Select top 10 * Form Table1 where range
15. Note: select all the information of the largest record of a corresponding to the data with the same B value in each group (similar usage can be used for the monthly ranking of the forum and Analysis of popular products each month, rank by subject score, etc .)
Select a, B, c from tablename Ta where a = (select max (a) from tablename TB where TB. B = TA. B)
16. Description: includes all rows in tablea but not in tableb and tablec and removes all repeated rows to derive a result table.
(Select a from tablea) Before t (select a from tableb) Before t (select a from tablec)
17. Description: 10 data records are randomly taken out.
Select top 10 * From tablename order by newid ()
18. Description: randomly selected records
Select newid ()
19. Note: delete duplicate records
Delete from tablename where id not in (select max (ID) from tablename group by col1, col2 ,...)
20. Description: Lists All table names in the database.
Select name from sysobjects where type = 'U'
21. Note: List all
Select name from syscolumns where id = object_id ('tablename ')
22. Description: lists the fields of type, vender, and PCs, which are arranged by the Type field. case can be easily selected, similar to case in select.
Select Type, sum (Case vender when 'a then PCs else 0 end), sum (Case vender when 'C' then PCs else 0 end ), sum (Case vender when 'B' then PCs else 0 end) from tablename group by type
Display result:
Type vender PCs
Computer A 1
Computer A 1
Cd B 2
Cd a 2
Mobile phone B 3
Mobile phone C 3
23. Description: Initialize table 1.
Truncate table Table1
24. Description: select a record from 10 to 15.
Select top 5 * from (select top 15 * from Table order by id asc) Table _ alias order by ID DESC
Method for randomly selecting database records (using the randomize function and using SQL statements)
For the data stored in the database, random numbers provide the above results, but they may be too slow. You cannot ask ASP to "find a random number" and print it out. In fact, a common solution is to create a loop as follows:
Randomize
Rnumber = int (rndx 499) + 1
While not objrec. EOF
If objrec ("ID") = rnumber then
... The execution script...
End if
Objrec. movenext
Wend
This is easy to understand. First, you get a random number ranging from 1 to 500 (assuming 500 is the total number of records in the database ). Then, you traverse each record to test the id value and check whether it matches the rnumber. If conditions are met, the code starting with the then keyword is executed. If your rnumber is equal to 495, it takes a long time to repeat the database. Although the number 500 looks a little larger, it is still a small database than a more robust enterprise solution, which usually contains thousands of records in a database. At this time, it will not die?
With SQL, you can quickly find an accurate record and open a recordset that only contains the record, as shown below:
Randomize
Rnumber = int (rndx 499) + 1
SQL = "select * from MERs where id =" & rnumber
Set objrec = objconn. Execute (SQL)
Response. writernumber & "=" & objrec ("ID") & "& objrec (" c_email ")
You do not need to write rnumber and ID. You only need to check the matching conditions. As long as you are satisfied with the work of the above code, you can operate "random" records on demand. Recordset does not contain any other content, so you can quickly find the record you need, which greatly reduces the processing time.
Random Number again
Now you are determined to squeeze the last drop of the random function, you may retrieve multiple random records at a time or want to use records within a certain random range. By extending the standard random example above, you can use SQL to cope with the above two situations.
To retrieve several randomly selected records and place them in the same recordset, you can store three random numbers and query the database to obtain records matching these numbers:
SQL = "select * from MERs where id =" & rnumber & "or ID =" & rnumber2 & "or ID =" & rnumber3
If you want to select 10 records (maybe the list of 10 links at each page loading), you can use between or mathematical equations to select the first record and the appropriate number of incremental records. This operation can be completed in several ways, but the SELECT statement only shows one possibility (the ID here is the automatically generated number ):
SQL = "select * from MERs where ID between" & rnumber & "and" & rnumber & "+ 9"
Note: The above code is not executed to check whether there are 9 concurrent records in the database.
Read several records randomly, tested
Access Syntax: Select top 10 * from table name order by RND (ID)
SQL Server: Select Top N * from table name order by newid ()
Mysqlelect * from table name order by rand () limit n
Access left connection syntax (the left connection is used in recent development, access does not help anything, there is no access SQL instructions on the internet, only test by yourself, now write down for future check)
Syntax elect table1.fd1, Table1, fd2, table2.fd2 from Table1 left join Table2 on table1.fd1, table2.fd1 where...
Use SQL statements to display long strings...
Syntax:
SQL database: Select case when Len (field)> 10 then left (field, 10) + '...' else field end as news_name, news_id from tablename
Access Database: Select IIF (LEN (field)> 2, left (field, 2) + '...', field) from tablename;
Conn. Execute description
Execute Method
This method is used to execute SQL statements. This method is used in the following two formats based on whether the record set is returned after an SQL statement is executed:
1. When an SQL query statement is executed, the query records are returned. Usage:
Set object variable name = connection object. Execute ("SQL query language ")
After the execute method is called, the record set object is automatically created and the query results are stored in the record object. The set method is used to assign the record set to the specified object for storage, later, the object variable represents the record set object.
2. When the SQL operator language is executed, no record set is returned. The usage is as follows:
Connection object. Execute "SQL operational statement" [, recordaffected] [, option]
· Recordaffected is optional. A variable can be placed here. After the SQL statement is executed, the number of valid records is automatically saved to the variable. By accessing this variable, you can know how many records the SQL statement team has performed.
· Option. The value of this parameter is generally adshorttext, which is used to tell ado that the first character after the execute method should be interpreted as the command text. You can specify this parameter to make execution more efficient.
· Begintrans, rollbacktrans, and committrans Methods