精典的SQL语句
数据库sql查询语句大全

数据库sql查询语句大全数据库SQL查询语句是用来从数据库中检索数据的命令。
以下是一些常见的SQL查询语句大全:1. SELECT语句,用于从数据库中选择数据。
例如,SELECT FROM 表名;2. WHERE子句,用于过滤数据,只返回满足特定条件的行。
例如,SELECT FROM 表名 WHERE 列名 = '条件';3. ORDER BY子句,用于对结果集按照指定列进行排序。
例如,SELECT FROM 表名 ORDER BY 列名;4. GROUP BY子句,用于对结果集按照指定列进行分组。
例如,SELECT 列名1, 列名2 FROM 表名 GROUP BY 列名1;5. HAVING子句,用于过滤分组后的数据。
例如,SELECT 列名1, COUNT(列名2) FROM 表名 GROUP BY 列名1 HAVING COUNT(列名2) > 10;6. JOIN子句,用于在多个表之间建立关联。
例如,SELECT FROM 表名1 INNER JOIN 表名2 ON 表名1.列名 = 表名2.列名;7. UNION操作符,用于合并两个或多个SELECT语句的结果集。
例如,SELECT 列名1 FROM 表名1 UNION SELECT 列名2 FROM 表名2;8. INSERT INTO语句,用于向数据库表中插入新记录。
例如,INSERT INTO 表名 (列1, 列2) VALUES (值1, 值2);9. UPDATE语句,用于更新数据库表中的记录。
例如,UPDATE 表名 SET 列名 = 值 WHERE 条件;10. DELETE FROM语句,用于从数据库表中删除记录。
例如,DELETE FROM 表名 WHERE 条件;以上是一些常见的SQL查询语句,它们可以帮助用户从数据库中检索、过滤、排序、分组和更新数据。
当然,SQL语言还有很多其他的功能和语法,这些只是其中的一部分。
SQL语句大全

简单基本的sql语句(1) 数据记录筛选:sql="select * from 数据表 where 字段名=字段值 order by 字段名[desc]"sql="select * from 数据表 where 字段名 like '%字段值%' order by 字段名 [desc]"sql="select top 10 * from 数据表 where 字段名=字段值 order by 字段名 [desc]"sql="select top 10 * from 数据表 order by 字段名 [desc]"sql="select * from 数据表 where 字段名 in ('值1','值2','值3')"sql="select * from 数据表 where 字段名 between 值1 and 值2"(2) 更新数据记录:sql="update 数据表 set 字段名=字段值 where 条件表达式"sql="update 数据表 set 字段1=值1,字段2=值2 …… 字段n=值n where 条件表达式"(3) 删除数据记录:sql="delete from 数据表 where 条件表达式"sql="delete from 数据表" (将数据表所有记录删除)(4) 添加数据记录:sql="insert into 数据表 (字段1,字段2,字段3 …) values (值1,值2,值3 …)"sql="insert into 目标数据表 select * from 源数据表" (把源数据表的记录添加到目标数据表)(5) 数据记录统计函数:AVG(字段名) 得出一个表格栏平均值COUNT(*;字段名) 对数据行数的统计或对某一栏有值的数据行数统计MAX(字段名) 取得一个表格栏最大的值MIN(字段名) 取得一个表格栏最小的值SUM(字段名) 把数据栏的值相加引用以上函数的方法:sql="select sum(字段名) as 别名 from 数据表 where 条件表达式"set rs=conn.excute(sql)用 rs("别名") 获取统计的值,其它函数运用同上。
基础sql语句

基础sql语句1. SELECT: 用于查询表中的数据,可以使用通配符(*)表示所有列或者指定列名。
例子:SELECT * FROM table_name;2. FROM: 用于指定查询的数据来源,即需要查询哪张表。
例子:SELECT * FROM table_name;3. WHERE: 用于筛选满足条件的数据行,可以使用比较运算符(>,<,=,!=,>=,<=)等。
例子:SELECT * FROM table_name WHEREcolumn_name >= 10;4. ORDER BY: 用于将查询结果按照某个列进行排序,可以指定升序或降序(ASC或DESC)。
例子:SELECT * FROM table_name ORDER BYcolumn_name ASC;5. GROUP BY: 用于将查询结果按照某个列进行分组,通常使用聚合函数(SUM,COUNT,AVG,MAX,MIN)进行数据计算。
例子:SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name;6. LIMIT: 用于限制查询结果的数量,只返回前几条数据。
例子:SELECT * FROM table_name LIMIT 10;7. JOIN: 用于将多张表按照共同的字段进行连接,可以有多种连接方式(INNER JOIN,LEFT JOIN,RIGHT JOIN,FULL OUTER JOIN)。
例子:SELECT * FROM table1 LEFT JOIN table2 ONtable1.column_name = table2.column_name.。
sql 数据加工 常用语句

sql 数据加工常用语句SQL数据加工是指对数据库中的数据进行查询、过滤、排序、统计等操作,以得到所需的结果。
下面是10个常用的SQL数据加工语句:1. SELECT语句:用于从数据库中选择指定的列或所有列的数据。
例如:SELECT * FROM table_name;2. WHERE语句:用于筛选满足指定条件的数据。
例如:SELECT * FROM table_name WHERE condition;3. ORDER BY语句:用于对查询结果按指定列进行排序。
例如:SELECT * FROM table_name ORDER BY column_name;4. GROUP BY语句:用于对查询结果按指定列进行分组。
例如:SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name;5. HAVING语句:与GROUP BY语句配合使用,在分组后对结果进行筛选。
例如:SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name HAVING COUNT(*) > 10;6. JOIN语句:用于将多个表的数据进行关联查询。
例如:SELECT * FROM table1 JOIN table2 ON table1.column_name = table2.column_name;7. UNION语句:用于将多个查询结果合并为一个结果集。
例如:SELECT column_name FROM table1 UNION SELECT column_name FROM table2;8. INSERT INTO语句:用于向数据库中插入新的数据。
例如:INSERT INTO table_name (column1, column2) VALUES (value1, value2);9. UPDATE语句:用于更新数据库中的数据。
sql经典语句(SQLclassicsentences)

sql经典语句(SQL classic sentences)I. Basic operation1) DESC, the describe role is to display the structure of the data table using the form: desc data table name2) distinct eliminates duplicate data usage: select, distinct, field name, from data table3) order by field 1 ASC, field 2 desc4) nested queries select, emp.empno, emp.ename, emp.job, emp.salFrom scott.empWhere sal>= (select, Sal, from, scott.emp, where, ename='WARD');5) nested queries select, emp.empno, emp.ename, emp.job, in, emp.salFrom scott.empWhere, Sal, in (select, Sal, from, scott.emp, where, ename ='WARD');6) nested queries select, emp.empno, emp.ename, emp.job, any, emp.salFrom scott.empWhere Sal > any (select, Sal, from, scott.emp, where, job='MANAGER');Equivalent to (1) select, Sal, from, scott.emp, where, job ='MANAGER'(2) select, emp.empno, emp.ename, emp.job, emp.salFrom scott.empData found in where Sal > (1) data a, or, Sal > (1), data found in B, or, Sal > (1), CEg:Select, Sal, from, scott.emp, where, job ='MANAGER'results; 12,10,13Equivalent to sal=12,10,13 or SAL> (12, OR, 10, OR, 13)7) the intersection operation is the intersection concept in the set. The sum of the elements that belong to the set A and belongs to the set B is the intersection. In the command edit area, execute the following statement.Eg:(select, djbh, from, ck_rwd_hz) intersect (select, djbh, from, ck_rwd_mx) documents numbered the sameSelect * from ck_rwd_mx a,((select, djbh, from, ck_rwd_hz) intersect (select, djbh, from, ck_rwd_mx)) BWhere a.djbh =b.djbhTwo function1) ceil takes the minimum integer ceil (N) greater than or equal to the value N; select, Mgr, mgr/100, ceil (mgr/100), from, scott.emp;2) floor takes the maximum integer floor (N) less than or equal to the value N; select, Mgr, mgr/100, floor (mgr/100), from, scott.emp;3) the remainder of mod m divisible by mod (m, n) n4) power, m, N, square, mod (m, n)5) round m four, five, keep the n bit mod (m, n)Select round (8.655,2) from dual; 8.66Select round (8.653,2) from dual; 8.656) sign n>0, take 1; n=0, take 0; n<0, take -1;7) AVG averages AVG (field name)8) count statistics total count (field name) select (*) from scott.emp; select count (distinct job) from scott.emp;9) min calculates numeric fields minimum, select, min (SAL), minimum salary from scott.emp;10) max calculates numeric field maximum, select, max (SAL), highest salary from scott.emp;11) sum calculates the sum of numeric fields, select, sum (SAL), the sum of salaries, from, scott.emp;Three input data1) single data entryInsert into data tables (fields 1, fields 2,...) valuse (field name 1 values, field name 2 values,...)Numeric fields can write values directly; character fields add single quotation marks; date fields add single quotes; at the same time pay attention to the order of days and months2) multi line data entryInsert into data table (field name 1, field name 2,...)(select (field name 1 or operation, field name 2 or operation,...) from data table where condition)3) data replication between tablesCreate table scott.testAs(Select, distinct, empno, ename, hiredate, from, scott.emp, where, empno>=7000);Create table spkpk_liu as select * from spkfk; creates tables and copies data, but creates incomplete table informationThis is all the way to full table backups.Usually after the table is built, you need to see if you want to build the index and primary key again.And "create, table, spkpk_liu, as, select * from, spkfk.""After this table is built, many of the parameter values of the table are the default minimum values, such as the initial value of the original table 10M, and the new table is probably only 256K.Formal environment used in the table, generally do not recommend such a table built.In this way, just a little lazy, if you do so,A statement can achieve the purpose of building tables and inserting data.For example, you need to modify the data in table A, and you might want to back up the data from the A table before you modify it.This time you can use create table... As...This makes it easy to retrieve data from the A table in the futureYou can do this when you debug your own program, but you can't create processes, packages, functions like thisFour delete dataDelete deletes data; truncate deletes the entire table data, but retains the structure1) delete recordsDelete from scott.test where empno and empno <=8000 > = 7500;2) delete the entire dataTruncate table scott.test;Similarities and differences between truncate, delete and dropNote: the delete here refers to the delete statement without the where clauseThe same thing: truncate and the delete without the where clause, and drop will delete the data in the tableDifference:1. truncate and delete only delete data and do not delete the structure of the table (definition)The drop statement will delete the structure of the table, the dependent constraints (constrain), the trigger, and the index (index); the stored procedure / function that depends on the table will be retained, but the invalid state will be changedThe 2.delete statement is DML, which is put into the rollback segement before the transaction is committed, and if you have the corresponding trigger, the execution will be triggeredTruncate, drop is DDL, the operation takes effect immediately, and the original data is not put into the rollback segment and cannot be rolled back. The operation does not trigger trigger.. Obviously, the drop statement releases all the space occupied by the table3. speed, in general: drop>, truncate > deleteOn use, you want to delete part of the data rows, with delete,take care to bring the where clause. The rollback section is large enough to be rolled back through the ROBACK, and there is considerable room for recoveryTo delete tables, of course, use dropYou want to keep the table and delete all the data. If you have nothing to do with the transaction, you can use truncate. Truncate, table, XX, delete the entire table of data, there is no room for recovery, the benefits can be arranged in the table debris, release spaceSo it's better to back up the data firstIf you are tidying up the inner fragments of a table, you can use truncate to catch up with reuse stroage and then import / insert data againFive update dataUpdate data sheetSet field name, 1=, new assignment, field name, 2=, new assignment,...Where conditionUpdate scott.empSet, empno=8888, ename='TOM', hiredate='03-9, -2002'Where empno = 7566;Update scott.empSet sal=(select, sal+300, from, scott.emp, where, empno = 8099)Where empno=8099;Decode (condition, value 1, translation value 1, value 2, translation value 2, value n, translation value n, default value)Six data export1 export the database TEST completely, export the user name system password manager to D:\daochu.dmpExpsystem/manager@TESTfile=d:\daochu.dmp full=y2 export the system user in the database to the table of the sys userExpsystem/manager@TESTfile=d:\daochu.dmp only wner= (system, Sys)3 export tables table1 and table2 from the databaseExpsystem/manager@TESTfile=d:\daochu.dmp tables= (table1, table2)4 export the field filed1 in the table table1 in the database to data that starts with "00"Expsystem/manager@TESTfile=d:\daochu.dmp tables= (table1) query=\ "where filed1 like'00%'\""Explmis_wh/lmis@lmisbuffer=10000 only WNER=lmis_wh rows=nfile=d:\lmis_wh_nodata.dmp log=d:\lmis_wh_nodata.logImplmis/lmis@lmisbuffer=10000, fromuser=lmis_wh, touser=lmis, file=d:\lmis_wh_nodata.dmp, log=d:\lmis_wh_nodata.logC:\>implmis/lmis@lmisbuffer=50000000, full=n,file=e:\daochu.dmp, ignore=y, rows=yCommit=y compile=y fromuser=lmis_wh touser=lmisSeven data import1 import data from the D:\daochu.dmp into the TEST database.Impsystem/manager@TEST file=d:\daochu.dmpThere may be a problem with it because some tables already exist, and then it is reported wrong, and the table is not imported.It's OK to add ignore=y at the back.2 import table table1 from d:\daochu.dmpImpsystem/manager@TEST file=d:\daochu.dmp tables= (table1)SQL definition: SQL is a database oriented general data processing language specification, can complete the following functions: data extraction query, insert modify delete data generation, modify and delete database objects, database security, database integrity control and data protection.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) DDL - database definition language: direct submission. CREATE: used to create database objects.DECLARE: in addition to creating temporary tables that are used only during the process, the DECLARE statements are very similar to the CREATE statements. The only object that can be declared is the table. And must be added to the user temporary tablespace.DROP: you can delete any object created with CREATE (database object) and DECLARE (table).ALTER: allows you to modify information about certain databaseobjects. Cannot modify index.Eight, the following is mainly based on object presentation of basic grammar1, database:Create database: CREATE, DATABASE, database-name, [USING, CODESET, codeset, TERRITORY, territory]Note: the code page problem.Delete database: drop, database, dbname2, table:Create new table:Create, table, tabname (col1, Type1, [not, null], [primary, key], col2, type2, [not, null],...)Create a new table based on the existing table:A:create, table, tab_new, like, tab_oldB:create, table, tab_new, as, select, col1, col2... From tab_old definition onlyModify table:Add a column:Alter, table, tabname, add, column, col, typeNote: column added will not be deleted. The DB2 column after the data type does not change, the only change is to increase the size of the varchar. Add primary key:Alter, table, tabname, add, primary, key (Col)Delete Primary key:Alter, table, tabname, drop, primary, key (Col)Delete table: drop, table, tabnameAlter table BMDOC_LIUFDrop constraint PK1_BMDOC cascade;3, table space:Create table spaces: create, tablespace, tbsname, PageSize, 4K, managed, by, database, using (file, file, size)Adding containers to tablespace: alter, tablespace, tablespace_name, add (file,'filename', size)Note: the operation is irreversible and will not be removed after adding the container. Therefore, when it is added, pay attention to it.Delete tablespace: drop, tablespace, tbsname4, index:Create indexes: create, [unique], index, idxname, on, tabname (col... ).Delete index: drop, index, idxnameNote: the index is not modifiable. If you want to change it, you must delete it.5 views:Create views: create, view, VIEWNAME, as, select, statementDelete view: drop view VIEWNAMENote: the only change to the view is the reference type column, which changes the range of columns. None of the other definitions can be modified. The view becomes invalid when the view is based on the base table drop.DML - the database manipulation language, which does not implicitly submit the current transaction and is committed to the setting of the visual environment.SELECT: querying data from tablesNote: the connection in the condition avoids Cartesian productDELETE: delete data from existing tablesUPDATE: update data for existing tablesINSERT: insert data into existing tablesNote: whether DELETE, UPDATE, and INSERT are submitted directly depends on the environment in which the statement is executed.Pay attention to the full transaction log when executing.2, DELETE: delete records from the tableSyntax format:DELETE, FROM, tablename, WHERE (conditions)3, INSERT: insert a record into the tableSyntax format:INSERT INTO tablename (col1, col2),... ) VALUES (value1, Value2),... );INSERT INTO tablename (col1, col2),... ) VALUES (value1, Value2),... ) (value1, value2,... ),......Insert does not wait for any program and does not cause locking4, UPDATE:Syntax format:UPDATE tabname SET (col1=values1, col2=values2),... (WHERE) (conditions);Note: update is slower and requires indexing on the corresponding column.Nine permissionsDCL - Data Control LanguageGRANT - Grant user permissionsREVOKE - revoke user rightsCOMMIT - commit transactions can permanently modify the databaseROLLBACK - rollback transactions, eliminating all changes made after the last COMMIT command, so that the contents of the database are restored to the state after the last COMMIT execution.1, GRANT: all or administrators assign access rights to other usersSyntax format:Grant [all privileges|privileges,... On tabname VIEWNAME to [public|user |,... .2 and REVOKE: cancel one of the user's access rightsSyntax format:Revoke [all privileges|privileges,... On tabname VIEWNAME from [public|user |,... .Note: any permissions of users of instance level cannot be canceled. They are not authorized by grant, but are permissions implemented by groups.3, COMMIT: permanently records changes made in the transaction to the database.Syntax format:Commit [work]4, ROLLBACK: will undo all changes made since the last submission.Syntax format:Rollback [work]Ten advanced SQL brief introductionFirst, the query between the use of computing wordsA:UNION operatorThe UNION operator derives a result table by combining two other result tables (such as TABLE1 and TABLE2) and eliminating any duplicate rows in the table.When ALL is used with UNION (that is, UNION ALL), the duplicate rows are not eliminated. In the two case, each row of the derived table does not come from TABLE1, or from TABLE2.B:EXCEPT operatorThe EXCEPT operator derives a result table by including all rows in TABLE1, but not in TABLE2, and eliminating all duplicate rows. When ALL is used with EXCEPT (EXCEPT ALL), the duplicate rows are not eliminated.C:INTERSECT operatorThe INTERSECT operator derives a result table by including only rows in TABLE1 and TABLE2 and eliminating all duplicate rows. When ALL is used with INTERSECT (INTERSECT ALL), the duplicate rows are not eliminated.Note: several query results lines using arithmetic words must be consistent.Appendix: introduction to commonly used functions1, type conversion function:Converted to a numeric type:Decimal, double, Integer, smallint, realHex (ARG): 16 hexadecimal representation converted into parameters.Converted to string type:Char, varcharDigits (ARG): returns the string representation of Arg, and Arg must be decimal.Converted to date or time:Date, time, timestamp2, time and date:Year, quarter, month, week, day, hour, minute, secondDayofyear (ARG): returns the daily value of Arg in the yearDayofweek (ARG): returns the daily value of Arg in the weekDays (ARG): the integer representation of the return date, the number of days from the 0001-01-01.Midnight_seconds (ARG): the number of seconds between midnight and arg.Monthname (ARG): returns the month name of arg.Dayname (ARG): the week that returns arg.3 string function:Length, lcase, ucase, ltrim, rtrimCoalesce (arg1, arg2)... ) returns the first non null parameter in the argument set.Concat (arg1, arg2): connect two strings, arg1 and arg2.Insert (arg1, POS, size, arg2): returns a arg1 that removes size characters from POS and inserts arg2 into that location.Left (Arg, length): returns the leftmost length string of arg.Locate (arg1, arg2, <, pos>): find the location of the first occurrence of arg1 in arg2, specify POS, and start looking for the location of the arg1 from the POS of arg2.Posstr (arg1, arg2): returns the position where arg2 first appeared in arg1.Repeat (arg1, num_times): returns the string arg1 repeated num_times times.Replace (arg1, arg2, ARG3): replace all arg2 in arg1 to arg3.Right (Arg, length): returns a string consisting of lengthbytes on the left of the arg.Space (ARG): returns a string containing Arg spaces.Substr (arg1, POS, <, length>): returns the length character at the start of the POS position in arg1, and returns the remaining characters if no length is specified.4. Mathematical function:Abs, count, Max, min, sumCeil (ARG): returns the smallest integer greater than or equal to arg.Floor (ARG): returns the smallest integer less than or equal to the parameter.Mod (arg1,Arg2) returns arg1 by the remainder of the arg2, with the same symbol as arg1.Rand (): returns a random number between 1 and 1.Power (arg1, arg2): returns the arg2 power of arg1.Round (arg1, arg2): four, five into the truncated processing, arg2 is the number of bits, if arg2 is negative, then the number of decimal points before four to five processing.Sigh (ARG): symbolic designator to return arg. -1,0,1 representation.Truncate (arg1, arg2): truncate arg1, arg2 is the number of digits, and if arg2 is negative, keep the arg2 bits before the arg1 decimal point.5, others:Nullif (arg1, arg2): returns if the 2 arguments are equal, otherwise the argument 1 is returned。
经典SQL语句大全(超全)

一、基础1、说明:创建数据库CREATE DATABASE database-name2、说明:删除数据库drop database dbname3、说明:备份sql server--- 创建备份数据的 deviceUSE masterEXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1. dat'--- 开始备份BACKUP DATABASE pubs TO testBack4、说明:创建新表create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)根据已有的表创建新表:A:create table tab_new like tab_old (使用旧表创建新表)B:create table tab_new as select col1,col2… from tab_old definition only5、说明:删除新表drop table tabname6、说明:增加一个列Alter table tabname add column col type注:列增加后将不能删除。
DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。
7、说明:添加主键:Alter table tabname add primary key(col)说明:删除主键: Alter table tabname drop primary key(col)8、说明:创建索引:create [unique] index idxname on tabname(col….) 删除索引:drop index idxname注:索引是不可更改的,想更改必须删除重新建。
9、说明:创建视图:create view viewname as select statement删除视图:drop view viewname10、说明:几个简单的基本的sql语句选择:select * from table1 where 范围插入:insert into table1(field1,field2) values(value1,value2)删除:delete from table1 where 范围更新:update table1 set field1=value1 where 范围查找:select * from table1 where field1 like ’%value1%’ ---like的语法很精妙,查资料!排序:select * from table1 order by field1,field2 [desc]总数:select count as totalcount from table1求和:select sum(field1) as sumvalue from table1平均:select avg(field1) as avgvalue from table1最大:select max(field1) as maxvalue from table1最小:select min(field1) as minvalue from table111、说明:几个高级查询运算词A:UNION 运算符UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。
常用的SQL语句

常用的SQL语句下面列举了一些我们在开发中常常会使用到的SQL语句,供大家参考学习。
1. 查询所有数据:SELECT * FROM table_name;2. 查询指定列数据:SELECT column1, column2 FROM table_name;3. 带条件查询:SELECT * FROM table_name WHERE condition;4. 带条件查询并排序:SELECT * FROM table_name WHERE condition ORDER BY column_name ASC/DESC;5. 带分组的查询:SELECT column1, COUNT(*) FROM table_name GROUP BY column1;6. 带分组和排序的查询:SELECT column1, COUNT(*) FROM table_name GROUP BY column1 ORDER BY COUNT(*) DESC;7. 带聚合函数的查询:SELECT AVG(column1), MAX(column2), MIN(column3) FROM table_name;8. 带子查询的查询:SELECT * FROM table_name WHERE column1 IN (SELECT column1 FROM other_table);9. 带连接条件的查询:SELECT * FROM table1 JOIN table2 ON table1.column1 = table2.column2;10. 带连接和排序条件的查询:SELECT * FROM table1 JOIN table2 ON table1.column1 = table2.column2 ORDER BY table1.column2 ASC;11. 带连接和分组条件的查询:SELECT * FROM table1 JOIN table2 ON table1.column1 = table2.column2 GROUP BY table1.column2;12. 带连接和聚合函数条件的查询:SELECT * FROM table1 JOIN table2 ON table1.column1 = table2.column2 GROUP BY table1.column2 HAVING AVG(table2.column3) > 0;13. 插入数据:INSERT INTO table_name (column1, column2) VALUES (value1, value2);14. 更新数据:UPDATE table_name SET column1 = value1 WHERE condition;15. 删除数据:DELETE FROM table_name WHERE condition;16. 清空表数据:TRUNCATE TABLE table_name;17. 创建表:CREATE TABLE table_name (column1 datatype, column2 datatype, ...);18. 修改表结构:ALTER TABLE table_name ADD column_name datatype;19. 删除表:DROP TABLE table_name;20. 查看表结构:DESCRIBE table_name;21. 查看表数据量:SELECT COUNT(*) FROM table_name;22. 查看表索引:SHOW INDEX FROM table_name;23. 创建索引:CREATE INDEX index_name ON table_name (column_name);24. 删除索引:DROP INDEX index_name ON table_name;25. 批量插入数据:INSERT INTO table_name (column1, column2) VALUES (value1, value2), (value3, value4), ...;26. 批量更新数据:UPDATE table_name SET column1 = value1 WHERE condition, column2 = value2 WHERE condition, ...;27. 批量删除数据:DELETE FROM table_name WHERE condition, ...;28. 分页查询:SELECT * FROM table_name LIMIT offset, limit;29. 子查询嵌套查询:(SELECT column1 FROM other_table WHERE condition) IN (SELECT column1 FROM another_table WHERE condition);30. UNION操作符查询:SELECT * FROM table1 UNION SELECT * FROM table2。
sql简单语句

sql简单语句
SQL(StructuredQueryLanguage)是一种用于数据库管理的编程语言,它可以用于创建、读取、更新和删除数据库中的数据。
以下是一些常用的 SQL 简单语句:
1. SELECT:用于从数据库中读取数据。
例如:SELECT * FROM 表名;
2. INSERT:用于向数据库中插入数据。
例如:INSERT INTO 表名(字段1, 字段2, ...) VALUES (值1, 值2, ...);
3. UPDATE:用于更新数据库中的数据。
例如:UPDATE 表名 SET 字段1 = 值1, 字段2 = 值2 WHERE 条件;
4. DELETE:用于删除数据库中的数据。
例如:DELETE FROM 表名 WHERE 条件;
5. CREATE:用于创建数据库或表。
例如:CREATE DATABASE 数据库名;
CREATE TABLE 表名 (字段1 数据类型1, 字段2 数据类型
2, ...);
6. DROP:用于删除数据库或表。
例如:DROP DATABASE 数据库名;
DROP TABLE 表名;
以上是 SQL 简单语句中的一部分,它们是使用 SQL 进行数据库
管理时必须掌握的基础知识。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
精典的SQL语句ffice ffice" />
1. 行列转换--普通
假设有张学生成绩表(CJ)如下
Name Subject Result
张三语文80
张三数学90
张三物理85
李四语文85
李四数学92
李四物理82
想变成
姓名语文数学物理
张三80 90 85
李四85 92 82
declare @sql var char(4000)
set @sql = 'select Name'
select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Res ult end) ['+Subject+']'
from (select distinct Subject from CJ) as a
select @sql = @sql+' from test group by name'
exec(@sql)
2. 行列转换--合并
有表A,
id pid
1 1
1 2
1 3
2 1
2 2
3 1
如何化成表B BR>id pid
1 1,2,3
2 1,2
3 1
创建一个合并的函数
create function fmerg(@id int)
returns var char(8000)
as
begin
declare @str var char(8000)
set @str=''
select @str=@str+','+cast(pid as var char) from 表A where id=@id se t @str=right(@str,len(@str)-1)
return(@str)
End
go
--调用自定义函数得到结果
select distinct id,dbo.fmerg(id) from 表A
3. 如何取得一个数据表的所有列名
方法如下:先从SYSTEMOBJECT系统表中取得数据表的SYSTEMID,然后再SYSCOL UMN表中取得该数据表的所有列名。
SQL语句如下:
declare @objid int,@objname char(40)
set @objname = 'tablename'
select @objid = id from sysobjects where id = object_id(@objname) select 'Column_name' = name from syscolumns where id = @objid order b y colid
是不是太简单了?呵呵不过经常用阿.
4. 通过SQL语句来更改用户的密码
修改别人的,需要sysadmin role
EXEC sp_password NULL, 'newpassword', 'User'
如果帐号为SA执行EXEC sp_password NULL, 'newpassword', sa
5. 怎么判断出一个表的哪些字段不允许为空?
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where IS_NULLABLE= 'NO' and TABLE_NAME=tablename
6. 如何在数据库里找到含有相同字段的表?
a. 查已知列名的情况
SELECT as TableName, as columnname
From syscolumns a INNER JOIN sysobjects b
ON a.id=b.id
AND b.type='U'
AND ='你的字段名字'
b. 未知列名查所有在不同表出现过的列名
Select As tablename, As columnname
From syscolumns s1, sysobjects o
Where s1.id = o.id
And o.type = 'U'
And Exists (
Select 1 From syscolumns s2
Where =
And s1.id <> s2.id
)
7. 查询第xxx行数据
假设id是主键:
select *
from (select top xxx * from yourtable) aa
where not exists(select 1 from (select top xxx-1 * from yourtable) bb where aa.id=bb.id)
如果使用游标也是可以的
fetch absolute [number] from [cursor_name]
行数为绝对行数
8. SQL Server日期计算
a. 一个月的第一天
SELECT DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)
b. 本周的星期一
SELECT DATEADD(wk, DATEDIFF(wk,0,getdate()), 0)
c. 一年的第一天
SELECT DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)
d. 季度的第一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate()), 0)
e. 上个月的最后一天
SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(mm,0,getdate()), 0))
f. 去年的最后一天
SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0))
g. 本月的最后一天
SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0))
h. 本月的第一个星期一
select DATEADD(wk, DATEDIFF(wk,0,
dateadd(dd,6-datepart(day,getdate()),getdate())
), 0)
i. 本年的最后一天
SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0))。