第 4 页 精妙Sql语句

合集下载

SQL语句大全大全(经典珍藏版)

SQL语句大全大全(经典珍藏版)

SQL语句大全--语句功能--数据操作SELECT --从数据库表中检索数据行和列INSERT --向数据库表添加新数据行DELETE --从数据库表中删除数据行UPDATE --更新数据库表中的数据-数据定义CREATE TABLE --创建一个数据库表DROP TABLE --从数据库中删除表ALTER TABLE --修改数据库表结构CREATE VIEW --创建一个视图DROP VIEW --从数据库中删除视图CREATE INDEX --为数据库表创建一个索引DROP INDEX --从数据库中删除索引CREATE PROCEDURE --创建一个存储过程DROP PROCEDURE --从数据库中删除存储过程CREATE TRIGGER --创建一个触发器DROP TRIGGER --从数据库中删除触发器CREATE SCHEMA --向数据库添加一个新模式DROP SCHEMA --从数据库中删除一个模式CREATE DOMAIN --创建一个数据值域ALTER DOMAIN --改变域定义DROP DOMAIN --从数据库中删除一个域--数据控制GRANT --授予用户访问权限DENY --拒绝用户访问REVOKE --解除用户访问权限--事务控制COMMIT --结束当前事务ROLLBACK --中止当前事务SET TRANSACTION --定义当前事务数据访问特征--程序化SQLDECLARE --为查询设定游标EXPLAN --为查询描述数据访问计划OPEN --检索查询结果打开一个游标FETCH --检索一行查询结果CLOSE --关闭游标PREPARE --为动态执行准备SQL 语句EXECUTE --动态地执行SQL 语句DESCRIBE --描述准备好的查询---局部变量declare @id char(10)--set @id = '10010001'select @id = '10010001'---全局变量---必须以@@开头--IF ELSEdeclare @x int @y int @z intselect @x = 1 @y = 2 @z=3if @x > @yprint 'x > y' --打印字符串'x > y'else if @y > @zprint 'y > z'else print 'z > y'--CASEuse panguupdate employeeset e_wage =casewhen job_level = .1. then e_wage*1.08 when job_level = .2. then e_wage*1.07 when job_level = .3. then e_wage*1.06 else e_wage*1.05end--WHILE CONTINUE BREAK declare @x int @y int @c intselect @x = 1 @y=1while @x < 3beginprint @x --打印变量x 的值while @y < 3beginselect @c = 100*@x + @yprint @c --打印变量c 的值select @y = @y + 1endselect @x = @x + 1select @y = 1end--WAITFOR--例等待1 小时2 分零3 秒后才执行SELECT 语句waitfor delay .01:02:03.select * from employee--例等到晚上11 点零8 分后才执行SELECT 语句waitfor time .23:08:00.select * from employee***SELECT***select *(列名) from table_name(表名) where column_name operator value ex:(宿主)select * from stock_information where stockid = str(nid)stockname = 'str_name'stockname like '% find this %'stockname like '[a-zA-Z]%' --------- ([]指定值的范围)stockname like '[^F-M]%' --------- (^排除指定范围)--------- 只能在使用like关键字的where子句中使用通配符)or stockpath = 'stock_path'or stocknumber < 1000and stockindex = 24not stock*** = 'man'stocknumber between 20 and 100stocknumber in(10,20,30)order by stockid desc(asc) --------- 排序,desc-降序,asc-升序order by 1,2 --------- by列号stockname = (select stockname from stock_information where stockid = 4)--------- 子查询--------- 除非能确保内层select只返回一个行的值,--------- 否则应在外层where子句中用一个in限定符select distinct column_name form table_name --------- distinct指定检索独有的列值,不重复select stocknumber ,"stocknumber + 10" = stocknumber + 10 from table_nameselect stockname , "stocknumber" = count(*) from table_name group by stockname--------- group by 将表按行分组,指定列中有相同的值having count(*) = 2 --------- having选定指定的组select *from table1, table2where table1.id *= table2.id -------- 左外部连接,table1中有的而table2中没有得以null表示table1.id =* table2.id -------- 右外部连接select stockname from table1union [all] ----- union合并查询结果集,all-保留重复行select stockname from table2***insert***insert into table_name (Stock_name,Stock_number) value ("xxx","xxxx")value (select Stockname , Stocknumber from Stock_table2)---value为select语句***update***update table_name set Stockname = "xxx" [where Stockid = 3]Stockname = defaultStockname = nullStocknumber = Stockname + 4***delete***delete from table_name where Stockid = 3truncate table_name ----------- 删除表中所有行,仍保持表的完整性drop table table_name --------------- 完全删除表***alter table*** --- 修改数据库表结构alter table database.owner.table_name add column_name char(2) null .....sp_help table_name ---- 显示表已有特征create table table_name (name char(20), age smallint, lname varchar(30))insert into table_name select ......... ----- 实现删除列的方法(创建新表)alter table table_name drop constraint Stockname_default ---- 删除Stockname的default约束***function(/*常用函数*/)***----统计函数----A VG --求平均值COUNT --统计数目MAX --求最大值MIN --求最小值SUM --求和--AVGuse panguselect avg(e_wage) as dept_avgWagefrom employeegroup by dept_id--MAX--求工资最高的员工姓名use panguselect e_namefrom employeewhere e_wage =(select max(e_wage)from employee)--STDEV()--STDEV()函数返回表达式中所有数据的标准差--STDEVP()--STDEVP()函数返回总体标准差--VAR()--VAR()函数返回表达式中所有值的统计变异数--VARP()--VARP()函数返回总体变异数----算术函数----/***三角函数***/SIN(float_expression) --返回以弧度表示的角的正弦COS(float_expression) --返回以弧度表示的角的余弦TAN(float_expression) --返回以弧度表示的角的正切COT(float_expression) --返回以弧度表示的角的余切/***反三角函数***/ASIN(float_expression) --返回正弦是FLOAT 值的以弧度表示的角ACOS(float_expression) --返回余弦是FLOAT 值的以弧度表示的角ATAN(float_expression) --返回正切是FLOAT 值的以弧度表示的角ATAN2(float_expression1,float_expression2)--返回正切是float_expression1 /float_expres-sion2的以弧度表示的角DEGREES(numeric_expression)--把弧度转换为角度返回与表达式相同的数据类型可为--INTEGER/MONEY/REAL/FLOAT 类型RADIANS(numeric_expression) --把角度转换为弧度返回与表达式相同的数据类型可为--INTEGER/MONEY/REAL/FLOAT 类型EXP(float_expression) --返回表达式的指数值LOG(float_expression) --返回表达式的自然对数值LOG10(float_expression)--返回表达式的以10 为底的对数值SQRT(float_expression) --返回表达式的平方根/***取近似值函数***/CEILING(numeric_expression) --返回>=表达式的最小整数返回的数据类型与表达式相同可为--INTEGER/MONEY/REAL/FLOAT 类型FLOOR(numeric_expression) --返回<=表达式的最小整数返回的数据类型与表达式相同可为--INTEGER/MONEY/REAL/FLOAT 类型ROUND(numeric_expression) --返回以integer_expression 为精度的四舍五入值返回的数据--类型与表达式相同可为INTEGER/MONEY/REAL/FLOAT 类型ABS(numeric_expression) --返回表达式的绝对值返回的数据类型与表达式相同可为--INTEGER/MONEY/REAL/FLOAT 类型SIGN(numeric_expression) --测试参数的正负号返回0 零值1 正数或-1 负数返回的数据类型--与表达式相同可为INTEGER/MONEY/REAL/FLOAT 类型PI() --返回值为π即3.1415926535897936RAND([integer_expression]) --用任选的[integer_expression]做种子值得出0-1 间的随机浮点数----字符串函数----ASCII() --函数返回字符表达式最左端字符的ASCII 码值CHAR() --函数用于将ASCII 码转换为字符--如果没有输入0 ~ 255 之间的ASCII 码值CHAR 函数会返回一个NULL 值LOWER() --函数把字符串全部转换为小写UPPER() --函数把字符串全部转换为大写STR() --函数把数值型数据转换为字符型数据LTRIM() --函数把字符串头部的空格去掉RTRIM() --函数把字符串尾部的空格去掉LEFT(),RIGHT(),SUBSTRING() --函数返回部分字符串CHARINDEX(),PA TINDEX() --函数返回字符串中某个指定的子串出现的开始位置SOUNDEX() --函数返回一个四位字符码--SOUNDEX函数可用来查找声音相似的字符串但SOUNDEX函数对数字和汉字均只返回0 值DIFFERENCE() --函数返回由SOUNDEX 函数返回的两个字符表达式的值的差异--0 两个SOUNDEX 函数返回值的第一个字符不同--1 两个SOUNDEX 函数返回值的第一个字符相同--2 两个SOUNDEX 函数返回值的第一二个字符相同--3 两个SOUNDEX 函数返回值的第一二三个字符相同--4 两个SOUNDEX 函数返回值完全相同QUOTENAME() --函数返回被特定字符括起来的字符串/*select quotename('abc', '{') quotename('abc')运行结果如下----------------------------------{{abc} [abc]*/REPLICATE() --函数返回一个重复character_expression 指定次数的字符串/*select replicate('abc', 3) replicate( 'abc', -2)运行结果如下----------- -----------abcabcabc NULL*/REVERSE() --函数将指定的字符串的字符排列顺序颠倒REPLACE() --函数返回被替换了指定子串的字符串/*select replace('abc123g', '123', 'def')运行结果如下----------- -----------abcdefg*/SPACE() --函数返回一个有指定长度的空白字符串STUFF() --函数用另一子串替换字符串指定位置长度的子串----数据类型转换函数----CAST() 函数语法如下CAST() (<expression> AS <data_ type>[ length ])CONVERT() 函数语法如下CONVERT() (<data_ type>[ length ], <expression> [, style])select cast(100+99 as char) convert(varchar(12), getdate())运行结果如下------------------------------ ------------199 Jan 15 2000----日期函数----DAY() --函数返回date_expression 中的日期值MONTH() --函数返回date_expression 中的月份值YEAR() --函数返回date_expression 中的年份值DA TEADD(<datepart> ,<number> ,<date>)--函数返回指定日期date 加上指定的额外日期间隔number 产生的新日期DA TEDIFF(<datepart> ,<number> ,<date>)--函数返回两个指定日期在datepart 方面的不同之处DA TENAME(<datepart> , <date>) --函数以字符串的形式返回日期的指定部分DA TEPART(<datepart> , <date>) --函数以整数值的形式返回日期的指定部分GETDA TE() --函数以DATETIME 的缺省格式返回系统当前的日期和时间----系统函数----APP_NAME() --函数返回当前执行的应用程序的名称COALESCE() --函数返回众多表达式中第一个非NULL 表达式的值COL_LENGTH(<'table_name'>, <'column_name'>) --函数返回表中指定字段的长度值COL_NAME(<table_id>, <column_id>) --函数返回表中指定字段的名称即列名DA TALENGTH() --函数返回数据表达式的数据的实际长度DB_ID(['database_name']) --函数返回数据库的编号DB_NAME(database_id) --函数返回数据库的名称HOST_ID() --函数返回服务器端计算机的名称HOST_NAME() --函数返回服务器端计算机的名称IDENTITY(<data_type>[, seed increment]) [AS column_name])--IDENTITY() 函数只在SELECT INTO 语句中使用用于插入一个identity column列到新表中/*select identity(int, 1, 1) as column_nameinto newtablefrom oldtable*/ISDATE() --函数判断所给定的表达式是否为合理日期ISNULL(<check_expression>, <replacement_value>) --函数将表达式中的NULL 值用指定值替换ISNUMERIC() --函数判断所给定的表达式是否为合理的数值NEWID() --函数返回一个UNIQUEIDENTIFIER 类型的数值NULLIF(<expression1>, <expression2>)--NULLIF 函数在expression1 与expression2 相等时返回NULL 值若不相等时则返回expression1 的值sql中的保留字action add aggregate allalter after and asasc avg avg_row_length auto_incrementbetween bigint bit binaryblob bool both bycascade case char characterchange check checksum columncolumns comment constraint createcross current_date current_time current_timestampdata database databases datedatetime day day_hour day_minuteday_second dayofmonth dayofweek dayofyeardec decimal default delayeddelay_key_write delete desc describedistinct distinctrow double dropend else escape escapedenclosed enum explain existsfields file first floatfloat4 float8 flush foreignfrom for full functionglobal grant grants grouphaving heap high_priority hourhour_minute hour_second hosts identifiedignore in index infileinner insert insert_id intinteger interval int1 int2int3 int4 int8 intoif is isam joinkey keys kill last_insert_idleading left length likelines limit load locallock logs long longbloblongtext low_priority max max_rowsmatch mediumblob mediumtext mediumintmiddleint min_rows minute minute_secondmodify month monthname myisamnatural numeric no notnull on optimize optionoptionally or order outeroutfile pack_keys partial passwordprecision primary procedure processprocesslist privileges read realreferences reload regexp renamereplace restrict returns revokerlike row rows secondselect set show shutdownsmallint soname sql_big_tables sql_big_selectssql_low_priority_updates sql_log_off sql_log_update sql_select_limit sql_small_result sql_big_result sql_warnings straight_joinstarting status string tabletables temporary terminated textthen time timestamp tinyblobtinytext tinyint trailing totype use using uniqueunlock unsigned update usagevalues varchar variables varyingvarbinary with write whenwhere year year_month zerofill查看全文常用SQL命令和ASP编程在进行数据库操作时,无非就是添加、删除、修改,这得设计到一些常用的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 * 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 …) valuess (值1,值2,值3 …)"sql="insert into 目标数据表select * from 源数据表" (把源数据表的记录添加到目标数据表)(5) 数据记录统计函数:A VG(字段名) 得出一个表格栏平均值COUNT(*|字段名) 对数据行数的统计或对某一栏有值的数据行数统计MAX(字段名) 取得一个表格栏最大的值MIN(字段名) 取得一个表格栏最小的值SUM(字段名) 把数据栏的值相加引用以上函数的方法:sql="select sum(字段名) as 别名from 数据表where 条件表达式"set rs=conn.excute(sql)用rs("别名") 获取统的计值,其它函数运用同上。

SQL语句总结

SQL语句总结

SQL语句总结一、插入记录1.插入固定的数值语法:INSERT [INTO] 表名[(字段列表)] VALUES(值列表)示例1:Insert into Students values('Mary’,24,’’)若没有指定给Student表的哪些字段插入数据:<情况一>表示给该表的所有字段插入数据,根据数据的个数,可以得知Students表中一共有3个字段<情况二>表中有4个字段,其中一个字段是标识列。

示例2:Insert into Students(Sname,Sage) values(‘Mary’,24)指定给表中的Sname,Sage两个字段插入数据。

注意事项:1)该命令运行一次向表中插入1条记录。

无法实现向已存在的某记录中插入一个数据2)如果不指定给哪些字段插入数值,则应注意值列表的值个数3)插入数据时,注意值的数据类型要与对应的字段数据类型匹配4)插入数据时,如果没有给值的字段必须保证允许其为空5)插入数据时,要注意字段中的一些约束2.插入的记录集为一个查询结果语法:INSERT INTO 表名[(字段列表)] SELECT 字段列表 FROM 表 WHERE 条件示例1:Insert into Teacher select Sname,Sage,Semail from Student从Student表中查询三个字段的全部记录,插入Teacher表,没有指定Teacher表的具体字段,表示给Teacher表的全部字段插入数值示例2:Insert into Teacher select Sname,Sage,Semail from Student where Sage>25从Student表中查询三个字段的部分记录,插入Teacher表示例3:Insert into Teacher(tid,tname)select Sname , Sage from Student从Student表中查询两个字段的全部记录,插入到Teacher表中的tid,tname字段注意事项:查询表的字段要和插入表的字段数据类型一一对应3.生成表查询语法:SELECT 字段列表 INTO 新表名 FROM 原表 WHERE 条件示例1:Select Sname,Sage,Semail into newStudent from Student where Sage<20 从Student表中查询出年龄小于20岁的学生的记录生成新表newStudent示例2:Select Sname,Sage,Semail into newStudent from Student where 1=2利用Student表的表结构生成新表newStudent,newStudent表中记录为空注意事项:执行该语句时,确保数据库中不存在into关键字后面的指定的表名二、删除记录1)删除满足条件的记录语法:DELETE FROM 表名 WHERE 条件示例1:Delete from Student where Sage<20从Student表中删除年龄小于20岁的学生的记录示例2:Delete from Student没有设置条件,删除Student表的全部记录2)删除表的全部记录语法:TRUNCATE TABLE 表名示例:Truncate table Student删除表Student中的全部记录,约束依然存在三、修改记录语法:UPDATE 表名 SET 字段=新值 WHERE 条件示例1:Update Student set Semail=’Email’+Semail where Semail is not null把有email的学员的email地址变为原先的地址前加上‘Email’字符串示例2:Update Student set Sage=Sage+1把所有记录的Sage变为原先的值加1,例如过一年学生要长一岁四、查询记录1.基本查询语法:SELECT 字段列表 FROM 表示例1:Select sName,sAge,sEmail from Students从Students表中查询3个字段的所有的记录示例2:Select * from Students从Students表中查询所有字段的所有的记录(字段列表位置写*代表查询表中所有字段)2.带WHERE子句的查询语法:SELECT 字段列表 FROM 表 WHERE 条件示例1:Select SName from Students where Sage>23查询Students表中年龄大于23的学员的姓名3.应用别名语法1:SELECT 字段列表 AS 别名……示例1:Select SName as 学员姓名,sAge as 学员年龄 from Students将查询的两个字段分别用中文别名显示语法2:SELECT 别名=字段……示例2:Select 学员姓名=sName, 学员年龄=sAge from Students注意事项:别名可以是英文,也可以是中文,别名可以用单引号引起,也可以不引4.使用常量(利用‘+’连接字段和常量)示例:Select sName+’的年龄是’+convert(varchar(2),sAge) as 学员信息from Students从Students表中查询,将学员的姓名和年龄信息与一个常量连接起来,显示为一个字段,该字段以“学员信息”为别名5.限制返回的行数语法1:SELECT TOP N 字段列表 FROM 表示例1:Select top 3 sName,sAge from Students查询Students表的前三条记录语法2:SELECT TOP N PERCENT 字段列表 FROM 表示例2:Select top 30 percent sName,sAge from Students查询Students表的前30%条记录6.排序语法:SELECT 字段列表 FROM 表 WHERE 条件 ORDER BY 字段 ASC/DESC示例1:Select * from Students where sAge>20 order by sAge查询年龄大于20岁的学员信息,并且按照年龄升序排序(若不指定升降序,默认为升序)示例2:Select * from Students order by sName desc查询所有学生的所有信息,并按照学生的姓名降序排序7.模糊查询1)Like:通常与通配符结合使用,适用于文本类型的字段示例1:Select * from Students where sName like ‘张_’查询Students表中张姓的,两个字名的学生信息示例2:Select * from Students where sName like ‘张%’查询Students表中张姓的学生的信息示例3:Select * from Students where sEmail like ‘%@[a-z]%’查询Students表中,Semail字段‘@’后的第一个字符为小写英文字母的学生信息示例4:Select * from Students where stuName like ‘%@[^a-z]%’查询Students表中,Semail字段‘@’后的第一个字符不是小写英文字母的学生信息2)Between …and …:用于查询条件为一个字段介于两个值之间示例:Select * from Students where Sage between 20 and 25查询学员年龄在20到25之间的学员信息3)In:用于查询某个字段在值列表中出现作为条件示例:Select * from Students where Scity in (‘大连’,’沈阳’,’北京’) 查询学员的城市在大连,沈阳或北京的学员信息,等价于如下功能:Select * from Students where Scity=’大连’or Scity=’沈阳’or Scity=’北京’4)Is null:用于查询某个字段为空作为条件示例:Select * from Students where Semail is null查询学员的email为空的学员信息Select * from Students where semail is not null查询学员的email不为空的学员信息8.聚合函数(所有函数自动忽略空值)1)Sum():统计某字段的和,用于数值型数据示例:Select sum(Sage) as 学员的年龄和 from Student统计Students表中所有学员的年龄总和,显示结果为一个字段一条记录2)Avg():统计某字段的平均值,用于数值型数据示例:Select avg(Sage) as 学员的平均年龄 from Students统计Students表中所有学员的年龄的平均值,显示结果为一个字段一条记录3)Max():统计某字段的最大值,用于数值,文本,日期型4)Min():统计某字段的最小值,用于数值,文本,日期型示例:Select max(Sage) as 最大年龄 , min(Sage) as 最小年龄 from Students查询Students表中的学员的最大年龄和最小年龄,显示结果为两个字段一条记录5)Count():统计某字段的记录数或者表的记录数示例1:Select count(Semail) as email的数量 from Students查询Students表中,有email的学员的数量。

sql经典语句(SQLclassicsentences)

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, &lt, 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, &lt, 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语句大全,精妙的sql使程序运行的更加流畅

SQL语句大全,精妙的sql使程序运行的更加流畅

SELECT A.NUM, , B.UPD_DATE, B.PREV_UPD_DATE
FROM TABLE1,
(SELECT X.NUM, X.UPD_DATE, Y.UPD_DATE PREV_UPD_DATE
FROM (SELECT NUM, UPD_DATE, INBOUND_QTY, STOCK_ONHAND
---局部变量
declare @id char(10)
--set @id = '10010001'
select @id = '10010001'
---全局变量
---必须以@@开头
--IF ELSE
declare @x int @y int @z int
select @x = 1 @y = 2 @z=3
说明:
从数据库中去一年的各单位电话费统计(电话费定额贺电化肥清单两个表来源)
SQL:
SELECT erper, a.tel, a.standfee, TO_CHAR(a.telfeedate, 'yyyy') AS telyear,
SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '01', a.factration)) AS JAN,
SQL: select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....
说明:得到表中最小的未使用的ID号
SQL:
TO_CHAR(TO_DATE(TO_CHAR(SYSDATE, 'YYYY/MM') &brvbar;&brvbar; '/01','YYYY/MM/DD') - 1, 'YYYY/MM') Y,

SQL查询语句大全集锦(经典)

SQL查询语句大全集锦(经典)

SQL查询语句大全集锦MYSQL查询语句大全集锦一、简单查询简单的Transact-SQL查询只包括选择列表、FROM子句和WHERE子句。

它们分别说明所查询列、查询的表或视图、以及搜索条件等。

例如,下面的语句查询testtable表中姓名为“张三”的nickname字段和email字段。

复制内容到剪贴板代码:SELECT `nickname`,`email`FROM `testtable`WHERE `name`='张三'(一) 选择列表选择列表(select_list)指出所查询列,它可以是一组列名列表、星号、表达式、变量(包括局部变量和全局变量)等构成。

1、选择所有列例如,下面语句显示testtable表中所有列的数据:复制内容到剪贴板代码:SELECT * FROM testtable2、选择部分列并指定它们的显示次序查询结果集合中数据的排列顺序与选择列表中所指定的列名排列顺序相同。

例如:复制内容到剪贴板代码:SELECT nickname,email FROM testtable3、更改列标题在选择列表中,可重新指定列标题。

定义格式为:列标题=列名列名列标题如果指定的列标题不是标准的标识符格式时,应使用引号定界符,例如,下列语句使用汉字显示列标题:复制内容到剪贴板代码:SELECT 昵称=nickname,电子邮件=email FROM testtable4、删除重复行SELECT语句中使用ALL或DISTINCT选项来显示表中符合条件的所有行或删除其中重复的数据行,默认为ALL。

使用DISTINCT选项时,对于所有重复的数据行在SELECT返回的结果集合中只保留一行。

5、限制返回的行数使用TOP n [PERCENT]选项限制返回的数据行数,TOP n说明返回n行,而TOP n PERCENT 时,说明n是表示一百分数,指定返回的行数等于总行数的百分之几。

例如:复制内容到剪贴板代码:SELECT TOP 2 * FROM `testtable`复制内容到剪贴板代码:SELECT TOP 20 PERCENT * FROM `testtable`(二) FROM子句FROM子句指定SELECT语句查询及与查询相关的表或视图。

精妙SQL语句介绍

精妙SQL语句介绍

精妙SQL语句介绍.数据类型数据类弄是数据的一种属性,表示数据所表示信息的类型。

任何一种计算机语言都定义了自己的数据类型。

当然,不同的程序语言都具有不同的特点,所定义的数据类型的各类和名称都或多或少有些不同。

SQL Server 提供了25 种数据类型:·Binary [(N)]·Varbinary [(N)]·Char [(N)]·Varchar[(N)]·Nchar[(N)]·Nvarchar[(N)]·Datetime·Smalldatetime·Decimal[(p[,s])]·Numeric[(p[,s])]·Float[(N)]·Real·Int·Smallint·Tinyint·Money·Smallmoney·Bit·Cursor·Sysname·Timestamp·Uniqueidentifier·Text·Image·Ntext(1)二进制数据类型二进制数据包括Binary、Varbinary 和Image.Binary 数据类型既可以是固定长度的(Binary),也可以是变长度的。

Binary[(N)] 是n 位固定的二进制数据。

其中,n 的取值范围是从1 到8000。

其存储窨的大小是n + 4 个字节。

Varbinary[(N)] 是n 位变长度的二进制数据。

其中,n 的取值范围是从1 到8000。

其存储窨的大小是n + 4个字节,不是n 个字节。

在Image 数据类型中存储的数据是以位字符串存储的,不是由SQL Server 解释的,必须由应用程序来解释。

例如,应用程序可以使用BMP、TIEF、GIF 和JPEG 格式把数据存储在Image 数据类型中。

高效SQL优化 非常好用的SQL语句优化34条

高效SQL优化 非常好用的SQL语句优化34条

1)选择最有效率的表名顺序(只在基于规则的优化器中有效):ORACLE 的解析器按照从右到左的顺序处理FROM子句中的表名,FROM子句中写在最后的表(基础表driving table)将被最先处理,在FROM子句中包含多个表的情况下,你必须选择记录条数最少的表作为基础表。

如果有3个以上的表连接查询, 那就需要选择交叉表(intersection table)作为基础表, 交叉表是指那个被其他表所引用的表.(2)WHERE子句中的连接顺序.:ORACLE采用自下而上的顺序解析WHERE子句,根据这个原理,表之间的连接必须写在其他WHERE条件之前, 那些可以过滤掉最大数量记录的条件必须写在WHERE子句的末尾. (3)SELECT子句中避免使用… * …:ORACLE在解析的过程中, 会将'*' 依次转换成所有的列名, 这个工作是通过查询数据字典完成的, 这意味着将耗费更多的时间(4)减少访问数据库的次数:ORACLE在内部执行了许多工作: 解析SQL语句, 估算索引的利用率, 绑定变量, 读数据块等;(5)在SQL*Plus , SQL*Forms和Pro*C中重新设置ARRAYSIZE参数, 可以增加每次数据库访问的检索数据量,建议值为200(6)使用DECODE函数来减少处理时间:使用DECODE函数可以避免重复扫描相同记录或重复连接相同的表.(7)整合简单,无关联的数据库访问:如果你有几个简单的数据库查询语句,你可以把它们整合到一个查询中(即使它们之间没有关系)(8)删除重复记录:最高效的删除重复记录方法( 因为使用了ROWID)例子:DELETE FROM EMP E WHERE E.ROWID > (SELECT MIN(X.ROWID) FROM EMP X WHERE X.EMP_NO = E.EMP_NO);(9)用TRUNCATE替代DELETE:当删除表中的记录时,在通常情况下, 回滚段(rollback segments ) 用来存放可以被恢复的信息. 如果你没有COMMIT事务,ORACLE会将数据恢复到删除之前的状态(准确地说是恢复到执行删除命令之前的状况) 而当运用TRUNCATE时, 回滚段不再存放任何可被恢复的信息.当命令运行后,数据不能被恢复.因此很少的资源被调用,执行时间也会很短. (译者按: TRUNCATE只在删除全表适用,TRUNCATE是DDL不是DML)(10)尽量多使用COMMIT:只要有可能,在程序中尽量多使用COMMIT, 这样程序的性能得到提高,需求也会因为COMMIT所释放的资源而减少:COMMIT所释放的资源:a. 回滚段上用于恢复数据的信息.b. 被程序语句获得的锁c. redo log buffer 中的空间d. ORACLE为管理上述3种资源中的内部花费(11)用Where子句替换HAVING子句:避免使用HAVING子句, HAVING 只会在检索出所有记录之后才对结果集进行过滤. 这个处理需要排序,总计等操作. 如果能通过WHERE子句限制记录的数目,那就能减少这方面的开销. (非oracle中)on、where、having这三个都可以加条件的子句中,on是最先执行,where次之,having最后,因为on是先把不符合条件的记录过滤后才进行统计,它就可以减少中间运算要处理的数据,按理说应该速度是最快的,where也应该比having快点的,因为它过滤数据后才进行sum,在两个表联接时才用on的,所以在一个表的时候,就剩下where跟having比较了。

sql常用语句大全

sql常用语句大全

sql常用语句大全以下是SQL中常用的语句:1. 查询语句:用于从数据库中检索数据。

- SELECT语句:用于从表中选择数据。

- FROM语句:用于从表中选择数据。

- WHERE语句:用于筛选数据。

- ORDER BY语句:用于排序数据。

- BY语句:用于对查询结果进行分组和排序。

2. 更新语句:用于更新数据库中的数据。

- UPDATE语句:用于在表中更新数据。

- WHERE语句:用于指定更新条件。

- SET语句:用于更新数据。

3. 删除语句:用于在数据库中删除数据。

- DELETE语句:用于从表中删除数据。

- WHERE语句:用于指定删除条件。

4. 创建语句:用于创建数据库、表、索引等。

-CREATE TABLE语句:用于创建一个表。

- AS语句:用于为表命名并提供别名。

- CONSTRAINT语句:用于为表创建约束条件。

5. 插入语句:用于向数据库中插入数据。

-INSERT INTO语句:用于向表中插入数据。

- VALUES语句:用于指定插入的数据。

6. 数据定义语句:用于定义数据库中的数据模型。

- PRIMARY KEY语句:用于为表创建主键。

- FOREIGN KEY语句:用于为表创建外键。

- KEY语句:用于为表创建索引。

7. 查询优化语句:用于优化查询性能。

- ANSI JOIN语句:用于连接两个表。

- NOT NULL语句:用于指定字段是否为非空。

- UNIQUE KEY语句:用于指定字段是否唯一。

8. 视图语句:用于简化复杂的查询。

- 视图定义语句:用于定义视图。

- 视图查询语句:用于查询视图中的数据。

9. 存储过程语句:用于执行复杂的操作并将结果存储回数据库中。

- 存储过程定义语句:用于定义存储过程。

- 存储过程执行语句:用于执行存储过程。

以上是SQL中常用的语句列表,SQL语句的使用可以极大地提高数据库的性能和灵活性。

经典SQL语句

经典SQL语句
(2)数据操纵语言(DML) DML的命令用来改变数据库中的数据,它有3个 基本语句:INSERT (插入) 、UPDATE(修 改)、DELETE(删除)。
(3)数据定义语言(DDL)
DDL用来创建数据库中的各种对象,包括数据库 模式、表、视图、索引、同义词、聚簇等,它的 基本语句有:CREATE DATABASE、CREATE TABLE、CREATE VIEW、CREATE INDEX等。
第四章 SQL语句
本章要点:
SQL的语句类型
SQL的单表数据查询 SQL多表连接查询 数据操纵
4.1 SQL的语句类型
(1)查询语言(QL) 查询语言用来对已存在的数据库中的数据按照 指定的组合、条件表达式或排序进行检索。它 的基本结构是由SELECT子句、FROM子句、 WHERE子句组成的查询块。
SELECT A1,A2,…,An
FROM R1,R2,…,Rm
WHERE P
4.2.1 单表查询
一、选择表中若干列
1.查询指定的列
例1、查询全体学生的学号和姓名。
SELECT Sno,Sname
FROM Student
例2、查询全体学生的姓名、学号和所在系
SELECT Sname,Sno,Sdept
注:当一个学生有多门不及格课程时,只需列 出一个学号,因此这里使用DISTINCT
2)确定范围
确定范围的谓词为:BETWEEN…AND
格式为:
列名|表达式[NOT]BETWEEN 下限值 AND 上限 值
BETWEEN…AND 一般用于对数值型数据和日 期型进行比较。列名或表达式的类型要与下限值 或上限值的类型相同。
5)涉及空值的查询 例20 查询没有考试成绩的学生的学号和相应的课程号 SELECT Sno,Cno

sql数据库语句

sql数据库语句

sql数据库语句
SQL(Structured Query Language)是一种结构化查询语言,用于存储,检索,更改和删除用户在关系型数据库系统(RDBMS)中存储的数据,是数据库开发的标准语言。

SQL语句旨在为用户提供使其可以执行特定任务的基本能力。

它们的主要目标是提供一种方便的方法,用于收集,存储,控制,重组和重新定位用户存储在数据库中的数据。

SQL语句可以用于查找,修改和更新数据库数据,创建和删除数据库对象,控制访问某些数据特定的对象,以及处理大量数据。

下面列举几个常见的SQL语句:
SELECT:语句用于从数据库表中检索数据;
DROP:语句用于从数据库中删除表和对象;
TRANSCATION:语句用于控制数据库事务;
GRANT:语句用于给指定标识符授予数据库对象访问权限;
SQL语句可以被用于控制,访问,管理和操作数据,并助于实现高效的数据结果集。

它的功能非常强大,但它的权限需要正确的分配和安全措施才能完全符合期望。

SQL常用语句一览

SQL常用语句一览

SQL常用语句一览SQL(Structured Query Language)是一种用于管理和操作关系型数据库的标准语言。

本文将介绍SQL中常用的语句,包括数据查询、数据插入、数据更新和数据删除等操作。

数据查询在SQL中,使用SELECT语句来查询数据。

下面是一些常用的数据查询语句:1.查询所有数据:SELECT * FROM table_name;2.查询指定列的数据:SELECT column1, column2, ... FROM table_name;3.查询带有条件的数据:SELECT * FROM table_name WHERE condition;4.查询排序后的数据:SELECT * FROM table_name ORDER BY column ASC/DESC;5.查询前N条数据:SELECT TOP N * FROM table_name;6.查询满足条件的唯一数据:SELECT DISTINCT column FROM table_name;数据插入在SQL中,使用INSERT语句将数据插入到表中。

下面是一些常用的数据插入语句:1.插入完整行数据:INSERT INTO table_name VALUES (value1, value2, ...);2.插入指定列的数据:INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);数据更新在SQL中,使用UPDATE语句更新表中的数据。

下面是一些常用的数据更新语句:1.更新指定列的数据:UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;数据删除在SQL中,使用DELETE语句删除表中的数据。

下面是一些常用的数据删除语句:1.删除满足条件的数据:DELETE FROM table_name WHERE condition;在SQL中,使用聚合函数来执行各种计算。

ssql经典语句

ssql经典语句

zhz20‎11 ‎常用‎S QL命令‎和ASP编‎程在进‎行数据库操‎作时,无非‎就是添加、‎删除、修改‎,这得设计‎到一些常用‎的SQL 语‎句,如下:‎SQL‎常用命令使‎用方法:‎(1) ‎数据记录筛‎选:s‎q l='s‎e lect‎* fr‎o m 数据‎表 whe‎r e 字段‎名=字段值‎orde‎r by ‎字段名 [‎d esc]‎'sql‎='sel‎e ct *‎from‎数据表‎w here‎字段名‎l ike ‎%字段值%‎orde‎r by ‎字段名[d‎e sc]'‎sql=‎'sele‎c t to‎p 10 ‎* fro‎m数据表‎wher‎e字段名‎orde‎r by ‎字段名 [‎d esc]‎'sql‎='sel‎e ct *‎from‎数据表‎w here‎字段名‎i n (值‎1,值2,‎值3)'‎s ql='‎s elec‎t * f‎r om 数‎据表 wh‎e re 字‎段名 be‎t ween‎值1 a‎n d 值2‎'(2‎)更新数‎据记录:‎sql=‎'upda‎t e 数据‎表 set‎字段名=‎字段值 w‎h ere ‎条件表达式‎'sql‎='upd‎a te 数‎据表 se‎t字段1‎=值1,字‎段2=值2‎…… 字‎段n=值n‎wher‎e条件表‎达式'‎(3) 删‎除数据记录‎:sq‎l='de‎l ete ‎f rom ‎数据表 w‎h ere ‎条件表达式‎'sql‎='del‎e te f‎r om 数‎据表' (‎将数据表所‎有记录删除‎)(4‎)添加数‎据记录:‎sql=‎'inse‎r t in‎t o 数据‎表 (字段‎1,字段2‎,字段3 ‎…) va‎l ues ‎(值1,值‎2,值3 ‎…)'s‎q l='i‎n sert‎into‎目标数据‎表 sel‎e ct *‎from‎源数据表‎' (把源‎数据表的记‎录添加到目‎标数据表)‎(5)‎数据记录‎统计函数:‎AVG‎(字段名)‎得出一个‎表格栏平均‎值COU‎N T(*|‎字段名) ‎对数据行数‎的统计或对‎某一栏有值‎的数据行数‎统计MA‎X(字段名‎)取得一‎个表格栏最‎大的值M‎I N(字段‎名) 取得‎一个表格栏‎最小的值‎S UM(字‎段名) 把‎数据栏的值‎相加引‎用以上函数‎的方法:‎s ql='‎s elec‎t sum‎(字段名)‎as 别‎名 fro‎m数据表‎wher‎e条件表‎达式's‎e t rs‎=conn‎.excu‎t e(sq‎l)用‎rs('‎别名') ‎获取统计的‎值,其它函‎数运用同上‎。

总结经典常用的SQL语句

总结经典常用的SQL语句

总结经典常用的SQL语句说明:复制表(只复制结构,源表名:a 新表名:b)SQL: select * into b from a where 1<>1说明:拷贝表(拷贝数据,源表名:a 目标表名:b)SQL: insert into b(a, b, c) select d,e,f from b;说明:显示文章、提交人和最后回复时间SQL: select a.title,ername,b.adddate from table a,(selectmax(adddate) adddate from table where table.title=a.title) b 说明:外连接查询(表名1:a 表名2:b)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说明:日程安排提前五分钟提醒SQL: select * from 日程安排where datediff(’minute’,f开始时间,getdate())>5说明:两张关联表,删除主表中已经在副表中没有的信息SQL:delete from info where not exists ( select * from infobz where info.infid=infobz.infid说明:--SQL:SELECT A.NUM, , B.UPD_DATE, B.PREV_UPD_DATEFROM TABLE1,(SELECT X.NUM, X.UPD_DATE, Y.UPD_DATE PREV_UPD_DATEFROM (SELECT NUM, UPD_DATE, INBOUND_QTY, STOCK_ONHANDFROM TABLE2WHERE TO_CHAR(UPD_DATE,’YYYY/MM’) = TO_CHAR(SYSDATE, ’YYYY/MM’)) X,(SELECT NUM, UPD_DATE, STOCK_ONHANDFROM TABLE2WHERE TO_CHAR(UPD_DATE,’YYYY/MM’) =TO_CHAR(TO_DATE(TO_CHAR(SYSDATE, ’YYYY/MM’)&brvbar;&brvbar; ’/01’,’YYYY/MM/DD’) - 1, ’YYYY/MM’) Y, WHERE X.NUM = Y.NUM (+)AND X.INBOUND_QTY + NVL(Y.STOCK_ONHAND,0) <> X.STOCK_ONHAND BWHERE A.NUM = B.NUM说明:--SQL:select * from studentinfo where not exists(select * from student where studentinfo.id=student.id) and 系名称=’"&strdepartmentname&"’ and 专业名称=’"&strprofessionname&"’ order by 性别,生源地,高考总成绩说明:从数据库中去一年的各单位电话费统计(电话费定额贺电化肥清单两个表来源)SQL:SELECT erper, a.tel, a.standfee, TO_CHAR(a.telfeedate, ’yyyy’) AS telyear,SUM(decode(TO_CHAR(a.telfeedate, ’mm’), ’01’, a.factration)) AS JAN,SUM(decode(TO_CHAR(a.telfeedate, ’mm’), ’02’, a.factration)) AS FRI,SUM(decode(TO_CHAR(a.telfeedate, ’mm’), ’03’, a.factration)) AS MAR,SUM(decode(TO_CHAR(a.telfeedate, ’mm’), ’04’, a.factration)) AS APR,SUM(decod e(TO_CHAR(a.telfeedate, ’mm’), ’05’, a.factration)) AS MAY,SUM(decode(TO_CHAR(a.telfeedate, ’mm’), ’06’, a.factration)) AS JUE,SUM(decode(TO_CHAR(a.telfeedate, ’mm’), ’07’, a.factration)) AS JUL,SUM(decode(TO_CHAR(a.telfeedate, ’mm’), ’08’, a.factrat ion)) AS AGU,SUM(decode(TO_CHAR(a.telfeedate, ’mm’), ’09’, a.factration)) AS SEP,SUM(decode(TO_CHAR(a.telfeedate, ’mm’), ’10’, a.factration)) AS OCT,SUM(decode(TO_CHAR(a.telfeedate, ’mm’), ’11’, a.factration)) AS NOV,SUM(decode(TO_CHAR(a.telfeedate, ’mm’), ’12’, a.factration)) AS DECFROM (SELECT erper, a.tel, a.standfee, b.telfeedate,b.factrationFROM TELFEESTAND a, TELFEE bWHERE a.tel = b.telfax) aGROUP BY erper, a.tel, a.standfee,TO_CHAR(a.telfeedate, ’yyyy’)说明:四表联查问题:SQL: select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....说明:得到表中最小的未使用的ID号SQL:SELECT (CASE WHEN EXISTS(SELECT * FROM Handle b WHERE b.HandleID = 1) THEN MIN(HandleID) + 1 ELSE 1 END) as HandleIDFROM HandleWHERE NOT HandleID IN (SELECT a.HandleID - 1 FROM Handle a)向表中添加一个新记录,你要使用SQL INSERT 语句。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

第4页精妙Sql语句精妙Sql语句1.判断a表中有而b表中没有的记录select a.* from tbl1 aleft join tbl2 bon a.key = b.keywhere b.key is null虽然使用in也可以实现,但是这种方法的效率更高一些2.新建一个与某个表相同结构的表select * into bfrom a where 1<>13.between的用法,between限制查询数据范围时包括了边界值,not between不包括select * from table1 where time between time1 and time2select a,b,c, from table1 where a not between 数值1 and 数值24. 说明:包括所有在TableA 中但不在TableB和T ableC 中的行并消除所有重复行而派生出一个结果表(select a from tableA ) except (select a from tableB) except (select a from tableC)5. 初始化表,可以将自增长表的字增长字段置为1TRUNCATE TABLE table16.多语言设置数据库或者表或者order by的排序规则--修改用户数据库的排序规则ater database dbname collate SQL_Latin1_General_CP1_CI_AS--修改字段的排序规则alter table a alter column c2 varchar(50) collate SQL_Latin1_General_CP1_CI_AS --按姓氏笔画排序select * from 表名order by 列名Collate Chinese_PRC_Stroke_ci_as--按拼音首字母排序select * from 表名order by 列名Collate Chinese_PRC_CS_AS_KS_WS7.列出所有的用户数据表:SELECT TOP 100 PERCENT AS 表名FROM dbo.syscolumns c INNER JOINdbo.sysobjects o ON o.id = c.id AND objectproperty(o.id, N'IsUserTable') = 1 AND <> 'dtproperties' LEFT OUTER JOINdbo.sysproperties m ON m.id = o.id AND m.smallid = c.colorderWHERE (c.colid = 1)ORDER BY , c.colid8.列出所有的用户数据表及其字段信息:SELECT TOP 100 PERCENT c.colid AS 序号, AS 表名, AS 列名, AS 类型, c.length AS 长度, c.isnullable AS 允许空,CAST(m.[value] AS Varchar(100)) AS 说明FROM dbo.syscolumns c INNER JOINdbo.sysobjects o ON o.id = c.id AND objectproperty(o.id, N'IsUserTable') = 1 AND <> 'dtproperties' INNER JOINdbo.systypes t ON t.xusertype = c.xusertype LEFT OUTER JOINdbo.sysproperties m ON m.id = o.id AND m.smallid = c.colorderORDER BY , c.colid9.Left,right Join的另外一种简洁的写法select * from a,b where a.id *= b.id --(*= 相当于LEFT JOIN)select * from a,b where a.id =* b.id --(=* 相当于Right JOIN)10.Update from 和delete from11.得到表中最小的未使用的ID号SELECT (CASE WHEN EXISTS(SELECT * FROM Handle b WHERE b.HandleID = 1)THEN MIN(HandleID) + 1 ELSE 1 END) as HandleIDFROM HandleWHERE NOT HandleID IN (SELECT a.HandleID - 1 FROM Handle a)12.随机取得记录SELECT TOP 10 * FROM T1 ORDER BY NEWID()精妙SQL语句介绍如何从一位菜鸟蜕变成为高手,灵活使用的SQL语句是必不可少的。

本文收集了部分比较经典,常用的SQL语句供大家参考,希望对大家有所帮助。

说明:复制表(只复制结构,源表名:a 新表名:b)SQL: select * into b from a where 1<>1说明:拷贝表(拷贝数据,源表名:a 目标表名:b)SQL: insert into b(a, b, c) select d,e,f from b;说明:显示文章、提交人和最后回复时间SQL: select a.title,ername,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b说明:外连接查询(表名1:a 表名2:b)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说明:日程安排提前五分钟提醒SQL: select * from 日程安排where datediff('minute',f开始时间,getdate())>5说明:两张关联表,删除主表中已经在副表中没有的信息SQL:delete from info where not exists ( select * from infobz where info.infid=infobz.infid说明:--SQL:SELECT A.NUM, , B.UPD_DATE, B.PREV_UPD_DATEFROM TABLE1,(SELECT X.NUM, X.UPD_DATE, Y.UPD_DATE PREV_UPD_DATEFROM (SELECT NUM, UPD_DATE, INBOUND_QTY, STOCK_ONHANDFROM TABLE2WHERE TO_CHAR(UPD_DATE,'YYYY/MM') = TO_CHAR(SYSDATE, 'YYYY/MM')) X,(SELECT NUM, UPD_DATE, STOCK_ONHANDFROM TABLE2WHERE TO_CHAR(UPD_DATE,'YYYY/MM') =TO_CHAR(TO_DATE(TO_CHAR(SYSDATE, 'YYYY/MM') || '/01','YYYY/MM/DD') - 1, 'YYYY/MM') Y,WHERE X.NUM = Y.NUM (+)AND X.INBOUND_QTY + NVL(Y.STOCK_ONHAND,0) <> X.STOCK_ONHAND BWHERE A.NUM = B.NUM说明:--SQL:select * from studentinfo where not exists(select * from student where studentinfo.id=student.id) and 系名称='"&strdepartmentname&"' and 专业名称='"&strprofessionname&"' order by 性别,生源地,高考总成绩说明:从数据库中去一年的各单位电话费统计(电话费定额贺电化肥清单两个表来源)SQL:SELECT erper, a.tel, a.standfee, TO_CHAR(a.telfeedate, 'yyyy') AS telyear,SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '01', a.factration)) AS JAN,SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '02', a.factration)) AS FRI,SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '03', a.factration)) AS MAR,SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '04', a.factration)) AS APR,SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '05', a.factration)) AS MAY,SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '06', a.factration)) AS JUE,SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '07', a.factration)) AS JUL,SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '08', a.factration)) AS AGU,SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '09', a.factration)) AS SEP,SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '10', a.factration)) AS OCT,SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '11', a.factration)) AS NOV,SUM(decode(TO_CHAR(a.telfeedate, 'mm'), '12', a.factration)) AS DECFROM (SELECT erper, a.tel, a.standfee, b.telfeedate, b.factrationFROM TELFEESTAND a, TELFEE bWHERE a.tel = b.telfax) aGROUP BY erper, a.tel, a.standfee, TO_CHAR(a.telfeedate, 'yyyy')说明:四表联查问题:SQL: select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....说明:得到表中最小的未使用的ID号SQL:SELECT (CASE WHEN EXISTS(SELECT * FROM Handle b WHERE b.HandleID = 1) THEN MIN(HandleID) + 1 ELSE 1 END) as HandleIDFROM HandleWHERE NOT HandleID IN (SELECT a.HandleID - 1 FROM Handle a)。

相关文档
最新文档