SQL statement set operation 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
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
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
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.