50个经典SQL语句
- 格式:docx
- 大小:20.49 KB
- 文档页数:12
SQL查询语句大全语句功能1、数据操作Select --从数据库表中检索数据行和列Insert --向数据库表添加新数据行Delete --从数据库表中删除数据行Update --更新数据库表中的数据2、数据定义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 --从数据库中删除一个域3、数据控制GRANT --授予用户访问权限DENY --拒绝用户访问REVOKE --解除用户访问权限4、事务控制COMMIT --结束当前事务ROLLBACK --中止当前事务SET TRANSACTION --定义当前事务数据访问特征5、程序化SQLDECLARE --为查询设定游标EXPLAN --为查询描述数据访问计划OPEN --检索查询结果打开一个游标FETCH --检索一行查询结果CLOSE --关闭游标PREPARE --为动态执行准备SQL 语句EXECUTE --动态地执行SQL 语句DESCRIBE --描述准备好的查询6、局部变量declare @id char(10)--set @id = '10010001'select @id = '10010001'7、全局变量---必须以@@开头8、IF 语句declare @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'9、CASE 语句use 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.05end10、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 = 1end11、WAITFOR语句--例等待1 小时2 分零3 秒后才执行Select 语句waitfor delay ’01:02:03’select * from employee--例等到晚上11 点零8 分后才执行Select 语句waitfor time ’23:08:00’select * from employee12、Select语句select *(列名) from table_name(表名) where column_name operator valueex:(宿主)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 stocksex = '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 table213、insert 语句insert into table_name (Stock_name,Stock_number) value ("xxx","xxxx")value (select Stockname , Stocknumber from Stock_table2)---value为select语句14、update语句update table_name set Stockname = "xxx" [where Stockid = 3]Stockname = defaultStockname = nullStocknumber = Stockname + 415、delete语句delete from table_name where Stockid = 3truncate table_name ----------- 删除表中所有行,仍保持表的完整性drop table table_name --------------- 完全删除表16、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约束17、常用函数----统计函数----AVG --求平均值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 间的随机浮点数18、字符串函数ASCII() --函数返回字符表达式最左端字符的ASCII 码值CHAR() --函数用于将ASCII 码转换为字符--如果没有输入0 ~ 255 之间的ASCII 码值CHAR 函数会返回一个NULL 值LOWER() --函数把字符串全部转换为小写UPPER() --函数把字符串全部转换为大写STR() --函数把数值型数据转换为字符型数据LTRIM() --函数把字符串头部的空格去掉RTRIM() --函数把字符串尾部的空格去掉LEFT(),RIGHT(),SUBSTRING() --函数返回部分字符串CHARINDEX(),PATINDEX() --函数返回字符串中某个指定的子串出现的开始位置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() --函数用另一子串替换字符串指定位置长度的子串19、数据类型转换函数----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 200020、日期函数----DAY() --函数返回date_expression 中的日期值MONTH() --函数返回date_expression 中的月份值YEAR() --函数返回date_expression 中的年份值DATEADD(<datepart> ,<number> ,<date>)--函数返回指定日期date 加上指定的额外日期间隔number 产生的新日期DATEDIFF(<datepart> ,<number> ,<date>)--函数返回两个指定日期在datepart 方面的不同之处DATENAME(<datepart> , <date>) --函数以字符串的形式返回日期的指定部分DATEPART(<datepart> , <date>) --函数以整数值的形式返回日期的指定部分GETDATE() --函数以DATETIME 的缺省格式返回系统当前的日期和时间21、系统函数----APP_NAME() --函数返回当前执行的应用程序的名称COALESCE() --函数返回众多表达式中第一个非NULL 表达式的值COL_LENGTH(<'table_name'>, <'column_name'>) --函数返回表中指定字段的长度值COL_NAME(<table_id>, <column_id>) --函数返回表中指定字段的名称即列名DATALENGTH() --函数返回数据表达式的数据的实际长度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 的值22、数学函数1.绝对值S:select abs(-1) valueO:select abs(-1) value from dual2.取整(大)S:select ceiling(-1.001) valueO:select ceil(-1.001) value from dual3.取整(小)S:select floor(-1.001) valueO:select floor(-1.001) value from dual4.取整(截取)S:select cast(-1.002 as int) valueO:select trunc(-1.002) value from dual5.四舍五入S:select round(1.23456,4) value 1.23460O:select round(1.23456,4) value from dual 1.23466.e为底的幂S:select Exp(1) value 2.7182818284590451O:select Exp(1) value from dual 2.718281827.取e为底的对数S:select log(2.7182818284590451) value 1O:select ln(2.7182818284590451) value from dual; 1 8.取10为底对数S:select log10(10) value 1O:select log(10,10) value from dual; 19.取平方S:select SQUARE(4) value 16O:select power(4,2) value from dual 1610.取平方根S:select SQRT(4) value 2O:select SQRT(4) value from dual 211.求任意数为底的幂S:select power(3,4) value 81O:select power(3,4) value from dual 8112.取随机数S:select rand() valueO:select sys.dbms_random.value(0,1) value from dual;13.取符号S:select sign(-8) value -1O:select sign(-8) value from dual -1----------数学函数14.圆周率S:Select PI() value 3.1415926535897931O:不知道15.sin,cos,tan 参数都以弧度为单位例如:select sin(PI()/2) value 得到1(SQLServer)16.Asin,Acos,Atan,Atan2 返回弧度17.弧度角度互换(SQLServer,Oracle不知道) DEGREES:弧度-〉角度RADIANS:角度-〉弧度---------数值间比较18. 求集合最大值S:select max(value) value from(select 1 valueunionselect -2 valueunionselect 4 valueunionselect 3 value)aO:select greatest(1,-2,4,3) value from dual19. 求集合最小值S:select min(value) value from(select 1 valueunionselect -2 valueunionselect 4 valueunionselect 3 value)aO:select least(1,-2,4,3) value from dual20.如何处理null值(F2中的null以10代替)S:select F1,IsNull(F2,10) value from TblO:select F1,nvl(F2,10) value from Tbl--------数值间比较21.求字符序号S:select ascii('a') valueO:select ascii('a') value from dual22.从序号求字符S:select char(97) valueO:select chr(97) value from dual23.连接S:select '11'+'22'+'33' valueO:select CONCAT('11','22')||33 value from dual 23.子串位置 --返回3S:select CHARINDEX('s','sdsq',2) valueO:select INSTR('sdsq','s',2) value from dual23.模糊子串的位置 --返回2,参数去掉中间%则返回7S:select patindex('%d%q%','sdsfasdqe') valueO:oracle没发现,但是instr可以通过第四霾问刂瞥鱿执问?BR>select INSTR('sdsfasdqe','sd',1,2) value from dual 返回624.求子串S:select substring('abcd',2,2) valueO:select substr('abcd',2,2) value from dual25.子串代替返回aijklmnefS:Select STUFF('abcdef', 2, 3, 'ijklmn') valueO:Select Replace('abcdef', 'bcd', 'ijklmn') value from dual26.子串全部替换S:没发现O:select Translate('fasdbfasegas','fa','我' ) value from dual27.长度S:len,datalengthO:length28.大小写转换 lower,upper29.单词首字母大写S:没发现O:select INITCAP('abcd dsaf df') value from dual30.左补空格(LPAD的第一个参数为空格则同space函数)。
一个项目涉及到的50个Sql语句(整理版)--1.学生表Student(S,Sname,Sage,Ssex) --S 学生编号,Sname 学生姓名,Sage 出生年月,Ssex 学生性别--2.课程表Course(C,Cname,T) --C --课程编号,Cname 课程名称,T 教师编号--3.教师表Teacher(T,Tname) --T 教师编号,Tname 教师姓名--4.成绩表SC(S,C,score) --S 学生编号,C 课程编号,score 分数*/--创建测试数据create table Student(S varchar(10),Sname nvarchar(10),Sage datetime,Ssex nvarchar(10)) insert into Student values('01' , N'赵雷' , '1990-01-01' , N'男')insert into Student values('02' , N'钱电' , '1990-12-21' , N'男')insert into Student values('03' , N'孙风' , '1990-05-20' , N'男')insert into Student values('04' , N'李云' , '1990-08-06' , N'男')insert into Student values('05' , N'周梅' , '1991-12-01' , N'女')insert into Student values('06' , N'吴兰' , '1992-03-01' , N'女')insert into Student values('07' , N'郑竹' , '1989-07-01' , N'女')insert into Student values('08' , N'王菊' , '1990-01-20' , N'女')create table Course(C varchar(10),Cname nvarchar(10),T varchar(10))insert into Course values('01' , N'语文' , '02')insert into Course values('02' , N'数学' , '01')insert into Course values('03' , N'英语' , '03')create table Teacher(T varchar(10),Tname nvarchar(10))insert into Teacher values('01' , N'张三')insert into Teacher values('02' , N'李四')insert into Teacher values('03' , N'王五')create table SC(S varchar(10),C varchar(10),score decimal(18,1))insert into SC values('01' , '01' , 80)insert into SC values('01' , '02' , 90)insert into SC values('01' , '03' , 99)insert into SC values('02' , '01' , 70)insert into SC values('02' , '02' , 60)insert into SC values('02' , '03' , 80)insert into SC values('03' , '01' , 80)insert into SC values('03' , '02' , 80)insert into SC values('03' , '03' , 80)insert into SC values('04' , '01' , 50)insert into SC values('04' , '02' , 30)insert into SC values('04' , '03' , 20)insert into SC values('05' , '01' , 76)insert into SC values('05' , '02' , 87)insert into SC values('06' , '01' , 31)insert into SC values('06' , '03' , 34)insert into SC values('07' , '02' , 89)insert into SC values('07' , '03' , 98)go--1、查询"01"课程比"02"课程成绩高的学生的信息及课程分数--1.1、查询同时存在"01"课程和"02"课程的情况select a.* , b.score [课程'01'的分数],c.score [课程'02'的分数] from Student a , SC b , SC c where a.S = b.S and a.S = c.S and b.C = '01' and c.C = '02' and b.score > c.score--1.2、查询同时存在"01"课程和"02"课程的情况和存在"01"课程但可能不存在"02"课程的情况(不存在时显示为null)(以下存在相同内容时不再解释)select a.* , b.score [课程"01"的分数],c.score [课程"02"的分数] from Student aleft join SC b on a.S = b.S and b.C = '01'left join SC c on a.S = c.S and c.C = '02'where b.score > isnull(c.score,0)--2、查询"01"课程比"02"课程成绩低的学生的信息及课程分数--2.1、查询同时存在"01"课程和"02"课程的情况select a.* , b.score [课程'01'的分数],c.score [课程'02'的分数] from Student a , SC b , SC c where a.S = b.S and a.S = c.S and b.C = '01' and c.C = '02' and b.score < c.score--2.2、查询同时存在"01"课程和"02"课程的情况和不存在"01"课程但存在"02"课程的情况select a.* , b.score [课程"01"的分数],c.score [课程"02"的分数] from Student aleft join SC b on a.S = b.S and b.C = '01'left join SC c on a.S = c.S and c.C = '02'where isnull(b.score,0) < c.score--3、查询平均成绩大于等于60分的同学的学生编号和学生姓名和平均成绩select a.S , a.Sname , cast(avg(b.score) as decimal(18,2)) avg_scorefrom Student a , sc bwhere a.S = b.Sgroup by a.S , a.Snamehaving cast(avg(b.score) as decimal(18,2)) >= 60order by a.S--4、查询平均成绩小于60分的同学的学生编号和学生姓名和平均成绩--4.1、查询在sc表存在成绩的学生信息的SQL语句。
语录大全经典SQL语句大全1(仅用于SQlServer)法二:select top 0 * into b from a2、说明:拷贝表(拷贝数据,源表名:a目标表名:b) (Access可用)insert into b(a, b, c) select d,e,f from b;3、说明:跨数据库之间表的拷贝(详细数据使用肯定路径) (Access 可用)insert into b(a, b, c) select d,e,f from b in ‘详细数据库’ where条件例子:..from b in " where..4、说明:子查询(表名1:a表名2:b)select a,b,c from a where a IN (select d from b )或者: select a,b,c from a where a IN (1,2,3)5、说明:显示文章、提交人和最终回复时间selecta.title,ername,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b6、说明:外连接查询(表名1:a表名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.c7、说明:在线视图查询(表名1:a )select * from (SELECT a,b,c FROMa) T where t.a > 1;8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括select * from table1 where time between time1 and time2select a,b,c, from table1 where a not between数值1 and 数值29、说明:in的使用方法select * from tabl e1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)10、说明:两张关联表,删除主表中已经在副表中没有的信息delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )11、说明:四表联查问题:select * from a left inner join b ona.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where.....12、说明:日程支配提前五分钟提示SQL: select * from日程支配where datediff(minute,f开头时间,getdate())>513、说明:一条sql语句搞定数据库分页select top 10 b.* from (select top 20主键字段,排序字段from表名order by排序字段desc) a,表名b where b.主键字段= a.主键字段order by a.排序字段详细实现:关于数据库分页:declare @start int,@end int@sqlnvarchar(600)set @sql=’select top’+str(@end-@start+1)+’+from T where rid not in(select top’+str(@str-1)+’Rid from T where Rid>-1)’exec sp_executesql @sql留意:在top后不能直接跟一个变量,所以在实际应用中只有这样的进行特别的处理。
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。
mysql必背50条语句1. 创建数据库:```sqlCREATE DATABASE dbname;```2. 删除数据库:```sqlDROP DATABASE dbname;```3. 选择数据库:```sqlUSE dbname;```4. 显示所有数据库:```sqlSHOW DATABASES;```5. 创建表:```sqlCREATE TABLE tablename (column1 datatype,column2 datatype,...);```6. 查看表结构:```sqlDESC tablename;```7. 删除表:```sqlDROP TABLE tablename;```8. 插入数据:```sqlINSERT INTO tablename (column1, column2, ...) VALUES (value1, value2, ...);```9. 查询数据:```sqlSELECT * FROM tablename;```10. 条件查询:```sqlSELECT * FROM tablename WHERE condition;```11. 更新数据:```sqlUPDATE tablename SET column1 = value1, column2 = value2 WHERE condition;```12. 删除数据:```sqlDELETE FROM tablename WHERE condition;```13. 查找唯一值:```sqlSELECT DISTINCT column FROM tablename;```14. 排序数据:```sqlSELECT * FROM tablename ORDER BY column ASC/DESC;```15. 限制结果集:```sqlSELECT * FROM tablename LIMIT 10;```16. 分页查询:```sqlSELECT * FROM tablename LIMIT 10 OFFSET 20;```17. 计算行数:```sqlSELECT COUNT(*) FROM tablename;```18. 聚合函数:```sqlSELECT AVG(column), SUM(column), MIN(column), MAX(column) FROM tablename;```19. 连接表:```sqlSELECT * FROM table1 INNER JOIN table2 ON table1.column = table2.column;```20. 创建索引:```sqlCREATE INDEX indexname ON tablename (column);```21. 查看索引:```sqlSHOW INDEX FROM tablename;```22. 删除索引:```sqlDROP INDEX indexname ON tablename;```23. 备份整个数据库:```sqlmysqldump -u username -p dbname > backup.sql;```24. 恢复数据库:```sqlmysql -u username -p dbname < backup.sql;```25. 修改表结构:```sqlALTER TABLE tablename ADD COLUMN newcolumn datatype;```26. 重命名表:```sqlRENAME TABLE oldname TO newname;```27. 增加主键:```sqlALTER TABLE tablename ADD PRIMARY KEY (column);```28. 删除主键:```sqlALTER TABLE tablename DROP PRIMARY KEY;```29. 增加外键:```sqlALTER TABLE tablename ADD CONSTRAINT fk_name FOREIGN KEY (column) REFERENCES othertable(column);```30. 删除外键:```sqlALTER TABLE tablename DROP FOREIGN KEY fk_name;```31. 查看活动进程:```sqlSHOW PROCESSLIST;```32. 杀死进程:```sqlKILL process_id;```33. 给用户授权:```sqlGRANT permission ON dbname.tablename TO 'username'@'host';```34. 撤销用户权限:```sqlREVOKE permission ON dbname.tablename FROM 'username'@'host';```35. 创建用户:```sqlCREATE USER 'username'@'host' IDENTIFIED BY 'password';```36. 删除用户:```sqlDROP USER 'username'@'host';```37. 修改用户密码:```sqlSET PASSWORD FOR 'username'@'host' = PASSWORD('newpassword');```38. 查看用户权限:```sqlSHOW GRANTS FOR 'username'@'host';```39. 启用外键约束:```sqlSET foreign_key_checks = 1;```40. 禁用外键约束:```sqlSET foreign_key_checks = 0;```41. 启用查询缓存:```sqlSET query_cache_type = 1;```42. 禁用查询缓存:```sqlSET query_cache_type = 0;```43. 查看服务器版本:```sqlSELECT VERSION();```44. 查看当前日期和时间:```sqlSELECT NOW();```45. 查找匹配模式:```sqlSELECT * FROM tablename WHERE column LIKE 'pattern';```46. 计算平均值:```sqlSELECT AVG(column) FROM tablename;```47. 查找空值:```sqlSELECT * FROM tablename WHERE column IS NULL;```48. 日期比较:```sqlSELECT * FROM tablename WHERE date_column > '2022-01-01';```49. 将结果导出为CSV 文件:```sqlSELECT * INTO OUTFILE 'output.csv' FIELDS TERMINATED BY ',' FROM tablename;```50. 将结果导入其他表:```sqlLOAD DATA INFILE 'input.csv' INTO TABLE tablename FIELDS TERMINATED BY ',';。
sql经典50题建表语句1、题目:创建一个名为"employees"的表,包含"id"、"name"和"salary"三个字段。
sql:CREATE TABLE employees (id INT PRIMARY KEY,name VARCHAR(50),salary DECIMAL(10, 2));2、题目:创建一个名为"orders"的表,包含"order_id"、"customer_id"和"order_date"三个字段。
sql:CREATE TABLE orders (order_id INT PRIMARY KEY,customer_id INT,order_date DATE);3、题目:创建一个名为"products"的表,包含"product_id"、"product_name"和"price"三个字段。
sql:CREATE TABLE products (product_id INT PRIMARY KEY,product_name VARCHAR(50),price DECIMAL(10, 2));4、题目:创建一个名为"customers"的表,包含"customer_id"、"first_name"、"last_name"和"email"四个字段。
sql:CREATE TABLE customers (customer_id INT PRIMARY KEY,first_name VARCHAR(50),last_name VARCHAR(50),email VARCHAR(100));5、题目:创建一个名为"addresses"的表,包含"address_id"、"street"、"city"和"state"四个字段。
(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( "别名") 获取统的计值,其它函数运用同上。
一、基础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],..)5、明:除新表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语句大全--语句功能--数据操作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 语句wai tfor 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_name select 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(/*常用函数*/)***----统计函数----AVG --求平均值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(),PATINDEX() --函数返回字符串中某个指定的子串出现的开始位置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 中的年份值DATEADD(<datepart> ,<number> ,<date>)--函数返回指定日期date 加上指定的额外日期间隔number 产生的新日期DATEDIFF(<datepart> ,<number> ,<date>)--函数返回两个指定日期在datepart 方面的不同之处DATENAME(<datepart> , <date>) --函数以字符串的形式返回日期的指定部分DATEPART(<datepart> , <date>) --函数以整数值的形式返回日期的指定部分GETDATE() --函数以DATETIME 的缺省格式返回系统当前的日期和时间----系统函数----APP_NAME() --函数返回当前执行的应用程序的名称COALESCE() --函数返回众多表达式中第一个非NULL 表达式的值COL_LENGTH(<'table_name'>, <'column_name'>) --函数返回表中指定字段的长度值COL_NAME(<table_id>, <column_id>) --函数返回表中指定字段的名称即列名DATALENGTH() --函数返回数据表达式的数据的实际长度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) 数据记录统计函数:AVG(字段名) 得出一个表格栏平均值COUNT(*|字段名) 对数据行数的统计或对某一栏有值的数据行数统计MAX(字段名) 取得一个表格栏最大的值MIN(字段名) 取得一个表格栏最小的值SUM(字段名) 把数据栏的值相加引用以上函数的方法:sql="select sum(字段名) as 别名from 数据表where 条件表达式"set rs=conn.excute(sql)用rs("别名") 获取统的计值,其它函数运用同上。
50个SQL语句及讲解1. SE LECT语句S E LE CT语句用于从数据库中选择数据。
S E LE CT*F RO M表名;该语句将返回表中的所有数据。
2. WH ERE语句W H ER E语句用于筛选满足指定条件的数据。
S E LE CT*F RO M表名W H ER E条件;可以使用比较运算符(如=、<、>)、逻辑运算符(如AN D、O R)以及通配符(如%、_)进行条件筛选。
3. OR DER BY语句O R DE RB Y语句用于对结果进行排序。
S E LE CT*F RO M表名O R DE RB Y列名A SC/D E SC;A S C表示升序排列,D E SC表示降序排列。
4. IN SERT INT O语句I N SE RT IN TO语句用于向数据库中插入新的数据。
I N SE RT IN TO表名(列1,列2,列3)V ALU E S(值1,值2,值3);将指定的数据插入到指定的列中。
5. UP DATE语句U P DA TE语句用于更新数据库中的数据。
U P DA TE表名SE T列名=新值WH ER E条件;更新满足条件的数据的指定列的值。
6. DE LETE语句D E LE TE语句用于从数据库中删除数据。
D E LE TE FR OM表名WH E RE条件;删除满足条件的数据。
7. LI KE语句L I KE语句用于在W HE R E语句中进行模糊匹配。
S E LE CT*F RO M表名W H ER E列名L IK E'ab c%';以匹配指定模式的数据。
8. DI STINCT语句D I ST IN CT语句用于返回唯一不重复的数据。
S E LE CT DI ST IN CT列名F RO M表名;返回指定列中的不重复数据。
9. GR OUP BY语句G R OU PB Y语句用于按照指定列对数据进行分组。
S E LE CT列1,C OU NT(列2)FR OM表名GRO U PB Y列1;按列1的值分组,并计算每组中列2的数量。
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 语句wa itfor 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(/*常用函数*/)***----统计函数----AVG --求平均值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(),PATINDEX() --函数返回字符串中某个指定的子串出现的开始位置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 中的年份值DATEADD(<datepart> ,<number> ,<date>)--函数返回指定日期date 加上指定的额外日期间隔number 产生的新日期DATEDIFF(<datepart> ,<number> ,<date>)--函数返回两个指定日期在datepart 方面的不同之处DATENAME(<datepart> , <date>) --函数以字符串的形式返回日期的指定部分DATEPART(<datepart> , <date>) --函数以整数值的形式返回日期的指定部分GETDATE() --函数以DATETIME 的缺省格式返回系统当前的日期和时间----系统函数----APP_NAME() --函数返回当前执行的应用程序的名称COALESCE() --函数返回众多表达式中第一个非NULL 表达式的值COL_LENGTH(<'table_name'>, <'column_name'>) --函数返回表中指定字段的长度值COL_NAME(<table_id>, <column_id>) --函数返回表中指定字段的名称即列名DATALENGTH() --函数返回数据表达式的数据的实际长度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) 数据记录统计函数:AVG(字段名) 得出一个表格栏平均值COUNT(*|字段名) 对数据行数的统计或对某一栏有值的数据行数统计MAX(字段名) 取得一个表格栏最大的值MIN(字段名) 取得一个表格栏最小的值SUM(字段名) 把数据栏的值相加引用以上函数的方法:sql="select sum(字段名) as 别名from 数据表where 条件表达式"set rs=conn.excute(sql)用rs("别名") 获取统的计值,其它函数运用同上。
mysql 50条语句1. SELECT * FROM table_name;2. SELECT column1, column2 FROM table_name;3. SELECT column1, column2 FROM table_name WHERE condition;4. INSERT INTO table_name (column1, column2) VALUES (value1, value2);5. UPDATE table_name SET column1 = value1 WHERE condition;6. DELETE FROM table_name WHERE condition;7. SELECT COUNT(*) FROM table_name;8. SELECT column1, column2 FROM table_name ORDER BY column1 ASC;9. SELECT column1, column2 FROM table_name ORDER BY column1 DESC;10. SELECT column1, column2 FROM table_name WHERE column1 IN (value1, value2);11. SELECT column1, column2 FROM table_name WHERE column1 NOTIN (value1, value2);12. SELECT column1, column2 FROM table_name LIMIT 10;13. SELECT column1, column2 FROM table_name LIMIT 10 OFFSET 5;14. SELECT column1, column2 FROM table_name WHERE column1 LIKE 'value%';15. SELECT DISTINCT column1 FROM table_name;16. SELECT column1, AVG(column2) FROM table_name GROUP BY column1;17. SELECT column1, COUNT(column2) FROM table_name GROUP BY column1;18. SELECT column1, SUM(column2) FROM table_name GROUP BY column1;19. SELECT column1, MAX(column2) FROM table_name GROUP BY column1;20. SELECT column1, MIN(column2) FROM table_name GROUP BY column1;21. SELECT column1, column2 FROM table_name INNER JOIN table2ON table1.column = table2.column;22. SELECT column1, column2 FROM table_name LEFT JOIN table2 ON table1.column = table2.column;23. SELECT column1, column2 FROM table_name RIGHT JOIN table2 ON table1.column = table2.column;24. SELECT column1, column2 FROM table_name FULL JOIN table2 ON table1.column = table2.column;25. SELECT column1, column2 FROM table_name WHERE column1 BETWEEN value1 AND value2;26. SELECT column1, column2 FROM table_name WHERE column1 NOT BETWEEN value1 AND value2;27. SELECT column1, column2 FROM table_name WHERE column1 IS NULL;28. SELECT column1, column2 FROM table_name WHERE column1 IS NOT NULL;29. SELECT column1, column2 FROM table_name WHERE column1 = value1 OR column2 = value2;30. SELECT column1, column2 FROM table_name WHERE column1 = value1 AND column2 = value2;31. SELECT column1, column2 FROM table_name WHERE column1 = value1 XOR column2 = value2;32. SELECT column1, column2 FROM table_name WHERE column1 = value1 AND (column2 = value2 OR column2 = value3);33. SELECT column1, column2 FROM table_name WHERE column1 = value1 OR (column2 = value2 AND column2 = value3);34. SELECT column1, column2 FROM table_name WHERE column1 > value1;35. SELECT column1, column2 FROM table_name WHERE column1 >= value1;36. SELECT column1, column2 FROM table_name WHERE column1 < value1;37. SELECT column1, column2 FROM table_name WHERE column1 <= value1;38. SELECT column1, column2 FROM table_name WHERE column1 !=value1;39. SELECT column1, column2 FROM table_name WHERE column1 <> value1;40. SELECT column1, column2 FROM table_name WHERE column1 = value1 AND column2 IN (value2, value3);41. SELECT column1, column2 FROM table_name WHERE column1 = value1 OR column2 NOT IN (value2, value3);42. SELECT column1, column2 FROM table_name WHERE column1 = value1 AND (column2 LIKE 'value%' OR column2 LIKE '%value');43. SELECT column1, column2 FROM table_name WHERE column1 = value1 AND column2 BETWEEN value2 AND value3;44. SELECT column1, column2 FROM table_name WHERE column1 = value1 AND column2 IS NULL;45. SELECT column1, column2 FROM table_name WHERE column1 = value1 AND column2 IS NOT NULL;46. SELECT column1, column2 FROM table_name WHERE column1 = value1 AND column2 = value2 ORDER BY column2;47. SELECT column1, column2 FROM table_name WHERE column1 = value1 AND column2 = value2 GROUP BY column2;48. SELECT column1, column2 FROM table_name WHERE column1 = value1 AND column2 = value2 HAVING COUNT(*) > 1;49. SELECT column1, column2 FROM table_name WHERE column1 = value1 AND column2 = value2 LIMIT 5;50. SELECT column1, column2 FROM table_name WHERE column1 = value1 AND column2 = value2 OFFSET 10;。
50个SQL语句(MySQL版)建表插⼊数据本学期正在学习数据库,前段时间⽼师让我们做⼀下50个经典SQL语句,当时做的⽐较快,有⼀些也是百度的,⾃我感觉理解的不是很透彻。
所以从本篇随笔开始,我将进⾏50个经典SQL语句的复盘,加深理解。
答案仅供参考,不⼀定完全正确,若发现错误或有更好的,欢迎评论,互相交流,⼀起成长--------------------------表结构--------------------------student(StuId,StuName,StuAge,StuSex) 学⽣表teacher(TId,Tname) 教师表course(CId,Cname,C_TId) 课程表sc(SId,S_CId,Score) 成绩表----------------------------------------------------------建表:create database MySchool character set "utf8mb4";use MySchool;create table student(StuId varchar(5) primary key,StuName varchar(10) not null,StuAge int,StuSex char(2) not null);create table teacher(TId varchar(3) primary key,Tname varchar(10) not null);create table course(CId varchar(3) primary key,Cname varchar(20) not null,C_TId varchar(3) not null,FOREIGN KEY (C_TId) REFERENCES teacher(TId));create table sc(SId varchar(5) not null,FOREIGN KEY (SId) REFERENCES student(StuId),S_CId varchar(3) not null,FOREIGN KEY (S_CId) REFERENCES course(CId),Score float);插⼊数据:insert into student value('1000','张⽆忌',18,'男'),('1001','周芷若',19,'⼥'),('1002','杨过',19,'男'),('1003','赵敏',18,'⼥'),('1004','⼩龙⼥',17,'⼥'),('1005','张三丰',18,'男'),('1006','令狐冲',19,'男'),('1007','任盈盈',20,'⼥'),('1008','岳灵珊',19,'⼥'),('1009','韦⼩宝',18,'男'),('1010','康敏',17,'⼥'),('1011','萧峰',19,'男'),('1012','黄蓉',18,'⼥'),('1013','郭靖',19,'男'),('1014','周伯通',19,'男'),('1015','瑛姑',20,'⼥'),('1016','李秋⽔',21,'⼥'),('1017','黄药师',18,'男'),('1018','李莫愁',18,'⼥'),('1019','冯默风',17,'男'),('1020','王重阳',17,'男'),('1021','郭襄',18,'⼥');insert into teacher value('001','姚明'),('002','叶平'),('003','叶开'),('004','孟星魂'),('005','独孤求败'),('006','裘千仞'),('007','裘千尺'),('008','赵志敬'),('009','阿紫'),('010','郭芙蓉'),('011','佟湘⽟'),('012','⽩展堂'),('013','吕轻侯'),('014','李⼤嘴'),('015','花⽆缺'),('016','⾦不换'),('017','乔丹');insert into course value('001','企业管理','002'), ('002','马克思','008'),('003','UML','006'),('004','数据库','007'),('005','逻辑电路','006'),('006','英语','003'),('007','电⼦电路','005'),('008','思想概论','004'),('009','西⽅哲学史','012'),('010','线性代数','017'),('011','计算机基础','013'),('012','AUTO CAD制图','015'),('013','平⾯设计','011'),('014','Flash动漫','001'),('015','Java开发','009'),('016','C#基础','002'),('017','Oracl数据库原理','010');insert into sc value('1001','003',90),('1001','002',87),('1001','001',96),('1001','010',85),('1002','003',70),('1002','002',87),('1002','001',42),('1002','010',65),('1003','006',78),('1003','003',70),('1003','005',70),('1003','001',32),('1003','010',85),('1003','011',21),('1004','007',90),('1004','002',87),('1005','001',23),('1006','015',85),('1006','006',46),('1006','003',59),('1006','004',70),('1006','001',99),('1007','011',85),('1007','006',84),('1007','003',72),('1007','002',87),('1008','001',94),('1008','012',85),('1008','006',32),('1009','003',90),('1009','002',82),('1009','001',96),('1009','010',82), ('1009','008',92), ('1010','003',90), ('1010','002',87), ('1010','001',96), ('1011','009',24), ('1011','009',25), ('1012','003',30), ('1013','002',37), ('1013','001',16), ('1013','007',55), ('1013','006',42), ('1013','012',34), ('1000','004',16), ('1002','004',55), ('1004','004',42), ('1008','004',34), ('1013','016',86), ('1013','016',44), ('1000','014',75), ('1002','016',100), ('1004','001',83), ('1008','013',97);。
1.Create database database_name --创建数据库On primary --创建主数据文件:mdf(name=‘name1’,Filename=‘磁盘名:\文件夹名\name1.mdf’,Size=,Maxsize=,Filegrowth=),(name=‘name2’,--创建次要数据文件(可以创建多个次要数据文件):ndfFilename=‘磁盘名:\文件夹名\name2.ndf’,Size=,Maxsize=,Filegrowth=)Log on --创建日志文件(可以创建多个日志文件):ldf(name=‘name3’,Filename=‘磁盘名:\文件夹名\name3.ldf’,Size=,Maxsize=,Filegrowth=)注意:多个次要数据文件和日志文件之间用‘,’隔开。
主要文件,次要文件,日志文件可以放在不同的磁盘里2.创建表Create table table_name(列名1 类型,列名2 类型,列名3 类型)注意:1.创建外键时该列不能为空,一个表内只能有一个主键,可以有多唯一约束2.创建联合主键(只能创建表级约束)Foreign key (列名1,列名2)3.修改表示添加列、列约束、修改约束、删除约束、删除列、删除表Alter table table_name[add column_name date_type][add constraint_name for column_name][alter column column_name new_data_type][drop column column_name | drop constraint constraint_name]4.DMLl语句(insert,update,delete)Insert into (列名1,列名2,列名3.··)values (值1,值2,值3,···)Update 表名set 列名=exprestion where 条件语句Delete form title_name where 条件语句5.(1)查看表结构:exec sp_help 表名(2)查看表内容:select *(列名1,列名2,。
sql语录1. "数据库是计算机科学的灵魂。
" - Larry Ellison2. "数据就是一切。
" - Richard Campbell3. "我就是一个SQL驱动的机器。
" - Anonymous4. "SQL语言是计算机界的乐谱。
" - Chris Date5. "如果你不懂数据库,你就不懂计算机。
" - Roy Thomas Fielding6. "无论你使用什么编程语言,了解SQL都是必不可少的。
" - John Ousterhout7. "SQL是一个强大而精确的工具,可以让你从海量数据中提取有价值的信息。
" - Anonymous8. "通过SQL,你可以与数据库交流,就像与一个聪明的机器对话一样。
" - Anonymous9. "SQL是数据的魔术师,可以在你眨眼的间隙内完成惊人的计算。
" - Anonymous10. "SQL不仅仅是一种语言,还是一种思维方式。
" - Joe Celko11. "SQL就是一种艺术,可以将你的数据变成有用的信息。
" - Anonymous12. "SQL是获得信息宝藏的秘密钥匙。
" - Anonymous13. "无论你是管理数据还是分析数据,SQL都是你的得力助手。
" - Anonymous14. "SQL的美妙之处在于它的简洁与高效。
" - Anonymous15. "通过SQL,你可以轻松地完成复杂的数据操作,提高工作效率。
" - Anonymous。
sql基础语句50条 curdate() 获取当前⽇期年⽉⽇curtime() 获取当前时间时分秒sysdate() 获取当前⽇期+时间年⽉⽇时分秒*/order by bonus desclimit (页码-1)*每页显⽰记录数, 每页显⽰记录数*/foreign key dept_id references dept(id)--指定外键-- ------------------------------------- ⼀、创建建数据库、创建建数据表、查看数据库、查看数据表-- ------------------------------------- 01.查看mysql服务器中所有数据库show databases;-- 02.进⼊某⼀数据库(进⼊数据库后,才能操作库中的表和表记录)use (库名) tast;-- 查看已进⼊的库select database();-- 03.查看当前数据库中的所有表-- 04.删除mydb1库-- 语法:drop database 库名;drop database (库名) test;-- 思考:当删除的表不存在时,如何避免错误产⽣?drop database (库名) if exists test;-- 05.重新创建mydb1库,指定编码为utf8-- 语法:create database 库名 charset 编码;create database mubatis12 charset utf8;-- 如果不存在则创建mydb1;create database if not exists mubatis12 charset utf8;-- 06.查看建库时的语句(并验证数据库库使⽤的编码)-- 语法:show create database 库名;show create database mybatis1;-- 07.进⼊mydb1库,删除stu学⽣表(如果存在)-- 语法:drop table 表名;drop table if exists stu;-- 08.创建stu学⽣表(编号[数值类型]、姓名、性别、出⽣年⽉、考试成绩[浮点型])/* 建表的语法:create table 表名(列名数据类型,列名数据类型,...); */create table stu(id int primary key auto_increment,name varchar(20),gender varchar(20),birthday date,score double );-- 09.查看stu学⽣表结构show create table stu;desc stu;-- ------------------------------------- ⼆、新增、修改、删除表记录 **********-- ------------------------------------- 10.往学⽣表(stu)中插⼊记录(数据)-- 插⼊记录:insert into 表名(列1,列2,列3...) values(值1,值2,值3...);insert into stu (id,name,gender,birthday,score) values(1,'Tony','⼥','1998-07-02',99.5);insert into stu values(2,'Ben','男','1998-07-03',90);insert into stu values(4,'张三','男','1998-07-08',70);insert into stu values(5,'李四','男','1998-07-09',59);insert into stu values(6,'桂花','⼥','1998-07-09',80);insert into stu values(7,'秀芹','⼥','1998-07-10',50);insert into stu values(8,'海燕','⼥','1999-5-4',91);/* 提⽰:设置编码:set names gbk;查看MySQL数据库使⽤的编码:show variables like 'char%';mysql --default-character-set=gbk -uroot -proot */-- 11.查询stu表所有学⽣的信息select*from stu;-- 12.修改stu表中所有学⽣的成绩,加10分特长分-- 修改语法: update 表名 set 列=值,列=值,列=值...;update stu set score=score+10;-- 13.修改stu表中王海涛的成绩,将成绩改为88分。
mysql sql语句面试经典50题1. 查询所有列的数据:```sqlSELECT * FROM table_name;```2. 条件查询:```sqlSELECT * FROM table_name WHERE condition;```3. 排序查询:```sqlSELECT * FROM table_name ORDER BY column_name ASC/DESC;```4. 去重查询:```sqlSELECT DISTINCT column_name FROM table_name;```5. 统计行数:```sqlSELECT COUNT(*) FROM table_name;```6. 条件统计:```sqlSELECT COUNT(*) FROM table_name WHERE condition;```7. 分组统计:```sqlSELECT column_name, COUNT(*) FROM table_name GROUP BY column_name;```8. 连接查询-内连接:```sqlSELECT * FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;```9. 连接查询-左连接:```sqlSELECT * FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;```10. 连接查询-右连接:```sqlSELECT * FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;```11. 子查询:```sqlSELECT column_name FROM table_name WHERE column_name = (SELECT column_name FROM another_table WHERE condition);```12. 更新数据:```sqlUPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;```13. 插入数据:```sqlINSERT INTO table_name (column1, column2) VALUES (value1, value2);```14. 删除数据:```sqlDELETE FROM table_name WHERE condition;```15. 模糊查询:```sqlSELECT * FROM table_name WHERE column_name LIKE 'pattern';```16. 使用通配符的模糊查询:```sqlSELECT * FROM table_name WHERE column_name LIKE '%pattern%';```17. 使用正则表达式的模糊查询:```sqlSELECT * FROM table_name WHERE column_name REGEXP 'pattern';```18. 限制结果集的行数:```sqlSELECT * FROM table_name LIMIT 10;```19. 跳过前N行:```sqlSELECT * FROM table_name LIMIT offset, count;```20. 计算平均值:```sqlSELECT AVG(column_name) FROM table_name;```21. 计算总和:```sqlSELECT SUM(column_name) FROM table_name;```22. 计算最大值和最小值:```sqlSELECT MAX(column_name), MIN(column_name) FROM table_name;```23. 使用CASE语句进行条件查询:```sqlSELECT column_name, CASE WHEN condition THEN 'value1' ELSE 'value2' END FROM table_name;```24. 使用GROUP BY和HAVING进行分组过滤:```sqlSELECT column_name, COUNT(*) FROM table_name GROUP BY column_name HAVING COUNT(*) > 1;```25. 多表更新:```sqlUPDATE table1 SET column1 = value1 WHERE column_name IN (SELECT column_name FROM table2 WHERE condition);```26. 多表删除:```sqlDELETE FROM table1 WHERE column_name IN (SELECT column_name FROM table2 WHERE condition);```27. 创建表:```sqlCREATE TABLE table_name (column1 datatype,column2 datatype,...);```28. 修改表结构-添加列:```sqlALTER TABLE table_name ADD column_name datatype;```29. 修改表结构-修改列数据类型:```sqlALTER TABLE table_name MODIFY column_name new_datatype;```30. 修改表结构-删除列:```sqlALTER TABLE table_name DROP COLUMN column_name;```31. 创建索引:```sqlCREATE INDEX index_name ON table_name (column_name);```32. 删除索引:```sqlDROP INDEX index_name ON table_name;```33. 使用LIMIT和OFFSET进行分页查询:```sqlSELECT * FROM table_name LIMIT page_size OFFSET (page_number - 1) * page_size;```34. 使用IFNULL处理空值:```sqlSELECT column1, IFNULL(column2, 'default_value') FROM table_name;```35. 使用COALESCE处理空值:```sqlSELECT column1, COALESCE(column2, 'default_value') FROM table_name;```36. 计算日期差:```sqlSELECT DATEDIFF(date1, date2) FROM table_name;```37. 获取当前日期和时间:```sqlSELECT NOW();```38. 获取唯一标识符:```sqlSELECT UUID();```39. 使用INNER JOIN和GROUP BY计算每个组的总数:```sqlSELECT table1.column_name, COUNT(*) FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name GROUP BY table1.column_name;```40. 使用CASE语句进行多条件查询:```sqlSELECT column_name, CASE WHEN condition1 THEN 'value1' WHEN condition2 THEN 'value2' ELSE 'value3' END FROM table_name;```41. 使用CONCAT连接字符串:```sqlSELECT CONCAT(column1, ' ', column2) AS concatenated_string FROM table_name;```42. 使用TRIM去除字符串两端的空格:```sqlSELECT TRIM(column_name) FROM table_name;```43. 使用LEFT和RIGHT截取字符串:```sqlSELECT LEFT(column_name, length) FROM table_name;SELECT RIGHT(column_name, length) FROM table_name;```44. 使用IN进行多值匹配:```sqlSELECT * FROM table_name WHERE column_name IN (value1, value2, value3);```45. 使用BETWEEN进行范围查询:```sqlSELECT * FROM table_name WHERE column_name BETWEEN value1 AND value2;```46. 使用COUNT和GROUP BY查找重复值:```sqlSELECT column_name, COUNT(*) FROM table_name GROUP BY column_name HAVING COUNT(*) > 1;```47. 使用DATE_FORMAT格式化日期:```sqlSELECT DATE_FORMAT(column_name, '%Y-%m-%d') FROM table_name;```48. 使用SUM和GROUP BY进行累计求和:```sqlSELECT column_name, SUM(column_name) OVER (ORDER BY column_name) AS running_total FROM table_name;```49. 使用CONVERT进行数据类型转换:```sqlSELECT column_name, CONVERT(column_name, new_datatype) FROM table_name;```50. 使用UPDATE和LIMIT进行分页更新:```sqlUPDATE table_name SET column1 = value1 LIMIT page_size OFFSET (page_number -1) * page_size;```。
50个经典SQL语句Student(S#,Sname,Sage,Ssex) 学生表Course(C#,Cname,T#) 课程表SC(S#,C#,score) 成绩表Teacher(T#,Tname) 教师表问题:1、查询“001”课程比“002”课程成绩高的所有学生的学号;select a.S# from (select s#,score from SC where C#='001') a,(select s#,score from SC where C#='002') bwhere a.score>b.score and a.s#=b.s#;2、查询平均成绩大于60分的同学的学号和平均成绩;select S#,avg(score)from scgroup by S# having avg(score) >60;3、查询所有同学的学号、姓名、选课数、总成绩;select Student.S#,Student.Sname,count(SC.C#),sum(score)from Student left Outer join SC on Student.S#=SC.S#group by Student.S#,Sname4、查询姓“李”的老师的个数;select count(distinct(Tname))from Teacherwhere Tname like '李%';5、查询没学过“叶平”老师课的同学的学号、姓名;select Student.S#,Student.Snamefrom Studentwhere S# not in (select distinct( SC.S#) from SC,Course,Teacher where SC.C#=Course.C# and Teacher.T#=Course.T# and Teacher.Tname='叶平');6、查询学过“001”并且也学过编号“002”课程的同学的学号、姓名;select Student.S#,Student.Sname from Student,SC where Student.S#=SC.S# and SC.C#='001'and exists( Select * from SC as SC_2 where SC_2.S#=SC.S# and SC_2.C#='002');7、查询学过“叶平”老师所教的所有课的同学的学号、姓名;select S#,Snamefrom Studentwhere S# in (select S# from SC ,Course ,Teacher where SC.C#=Course.C# and Teacher.T#=Course.T# and Teacher.Tname='叶平' group by S# having count(SC.C#)=(select count(C#) from Course,Teacher where Teacher.T#=Course.T# and Tname='叶平'));8、查询课程编号“002”的成绩比课程编号“001”课程低的所有同学的学号、姓名;Select S#,Sname from (select Student.S#,Student.Sname,score ,(select score from SC SC_2 where SC_2.S#=Student.S# and SC_2.C#='002') score2from Student,SC where Student.S#=SC.S# and C#='001') S_2 where score2 <score;9、查询所有课程成绩小于60分的同学的学号、姓名;select S#,Snamefrom Studentwhere S# not in (select Student.S# from Student,SC where S.S#=SC.S# and score>60);10、查询没有学全所有课的同学的学号、姓名;select Student.S#,Student.Snamefrom Student,SCwhere Student.S#=SC.S# group by Student.S#,Student.Sname having count(C#) <(select count(C#) from Course);11、查询至少有一门课与学号为“1001”的同学所学相同的同学的学号和姓名;select S#,Sname from Student,SC where Student.S#=SC.S# and C# in select C# from SC where S#='1001';12、查询至少学过学号为“001”同学所有一门课的其他同学学号和姓名;select distinct SC.S#,Snamefrom Student,SCwhere Student.S#=SC.S# and C# in (select C# from SC where S#='001');13、把“SC”表中“叶平”老师教的课的成绩都更改为此课程的平均成绩;update SC set score=(select avg(SC_2.score)from SC SC_2where SC_2.C#=SC.C# ) from Course,Teacher where Course.C#=SC.C# and Course.T#=Teacher.T# and Teacher.Tname='叶平');14、查询和“1002”号的同学学习的课程完全相同的其他同学学号和姓名;select S# from SC where C# in (select C# from SC where S#='1002')group by S# having count(*)=(select count(*) from SC where S#='1002');15、删除学习“叶平”老师课的SC表记录;Delect SCfrom course ,Teacherwhere Course.C#=SC.C# and Course.T#= Teacher.T# and Tname='叶平';16、向SC表中插入一些记录,这些记录要求符合以下条件:没有上过编号“003”课程的同学学号、2、号课的平均成绩;Insert SC select S#,'002',(Select avg(score)from SC where C#='002') from Student where S# not in (Select S# from SC where C#='002');17、按平均成绩从高到低显示所有学生的“数据库”、“企业管理”、“英语”三门的课程成绩,按如下形式显示:学生ID,,数据库,企业管理,英语,有效课程数,有效平均分SELECT S# as 学生ID,(SELECT score FROM SC WHERE SC.S#=t.S# AND C#='004') AS 数据库,(SELECT score FROM SC WHERE SC.S#=t.S# AND C#='001') AS 企业管理,(SELECT score FROM SC WHERE SC.S#=t.S# AND C#='006') AS 英语,COUNT(*) AS 有效课程数, AVG(t.score) AS 平均成绩FROM SC AS tGROUP BY S#ORDER BY avg(t.score)18、查询各科成绩最高和最低的分:以如下形式显示:课程ID,最高分,最低分SELECT L.C# As 课程ID,L.score AS 最高分,R.score AS 最低分FROM SC L ,SC AS RWHERE L.C# = R.C# andL.score = (SELECT MAX(IL.score)FROM SC AS IL,Student AS IMWHERE L.C# = IL.C# and IM.S#=IL.S#GROUP BY IL.C#)ANDR.Score = (SELECT MIN(IR.score)FROM SC AS IRWHERE R.C# = IR.C#GROUP BY IR.C#);19、按各科平均成绩从低到高和及格率的百分数从高到低顺序SELECT t.C# AS 课程号,max(ame)AS 课程名,isnull(AVG(score),0) AS 平均成绩,100 * SUM(CASE WHEN isnull(score,0)>=60 THEN 1 ELSE 0 END)/COUNT(*) AS 及格百分数FROM SC T,Coursewhere t.C#=course.C#GROUP BY t.C#ORDER BY 100 * SUM(CASE WHEN isnull(score,0)>=60 THEN 1 ELSE 0 END)/COUNT(*) DESC20、查询如下课程平均成绩和及格率的百分数(用"1行"显示): 企业管理(001),马克思(002),OO&UML (003),数据库(004)SELECT SUM(CASE WHEN C# ='001' THEN score ELSE 0 END)/SUM(CASE C# WHEN '001' THEN 1 ELSE 0 END) AS 企业管理平均分,100 * SUM(CASE WHEN C# = '001' AND score >= 60 THEN 1 ELSE 0 END)/SUM(CASE WHEN C# = '001' THEN 1 ELSE 0 END) AS 企业管理及格百分数,SUM(CASE WHEN C# = '002' THEN score ELSE 0 END)/SUM(CASE C# WHEN '002' THEN 1 ELSE 0 END) AS 马克思平均分,100 * SUM(CASE WHEN C# = '002' AND score >= 60 THEN 1 ELSE 0 END)/SUM(CASE WHEN C# = '002' THEN 1 ELSE 0 END) AS 马克思及格百分数,SUM(CASE WHEN C# = '003' THEN score ELSE 0 END)/SUM(CASE C# WHEN '003' THEN 1 ELSE 0 END) AS UML平均分,100 * SUM(CASE WHEN C# = '003' AND score >= 60 THEN 1 ELSE 0END)/SUM(CASE WHEN C# = '003' THEN 1 ELSE 0 END) AS UML及格百分数,SUM(CASE WHEN C# = '004' THEN score ELSE 0 END)/SUM(CASE C# WHEN '004' THEN 1 ELSE 0 END) AS 数据库平均分,100 * SUM(CASE WHEN C# = '004' AND score >= 60 THEN 1 ELSE 0 END)/SUM(CASE WHEN C# = '004' THEN 1 ELSE 0 END) AS 数据库及格百分数FROM SC21、查询不同老师所教不同课程平均分从高到低显示SELECT max(Z.T#) AS 教师ID,MAX(Z.Tname) AS 教师姓名,C.C# AS 课程ID,MAX(ame) AS 课程名称,AVG(Score) AS 平均成绩FROM SC AS T,Course AS C ,Teacher AS Zwhere T.C#=C.C# and C.T#=Z.T#GROUP BY C.C#ORDER BY AVG(Score) DESC22、查询如下课程成绩第3 名到第6 名的学生成绩单:企业管理(001),马克思(002),UML (003),数据库(004)[学生ID],[学生姓名],企业管理,马克思,UML,数据库,平均成绩SELECT DISTINCT top 3SC.S# As 学生学号,Student.Sname AS 学生姓名,T1.score AS 企业管理,T2.score AS 马克思,T3.score AS UML,T4.score AS 数据库,ISNULL(T1.score,0) + ISNULL(T2.score,0) + ISNULL(T3.score,0) + ISNULL(T4.score,0) as 总分FROM Student,SC LEFT JOIN SC AS T1ON SC.S# = T1.S# AND T1.C# = '001'LEFT JOIN SC AS T2ON SC.S# = T2.S# AND T2.C# = '002'LEFT JOIN SC AS T3ON SC.S# = T3.S# AND T3.C# = '003'LEFT JOIN SC AS T4ON SC.S# = T4.S# AND T4.C# = '004'WHERE student.S#=SC.S# andISNULL(T1.score,0) + ISNULL(T2.score,0) + ISNULL(T3.score,0) + ISNULL(T4.score,0)NOT IN(SELECTDISTINCTTOP 15 WITH TIESISNULL(T1.score,0) + ISNULL(T2.score,0) + ISNULL(T3.score,0) + ISNULL(T4.score,0)FROM scLEFT JOIN sc AS T1ON sc.S# = T1.S# AND T1.C# = 'k1'LEFT JOIN sc AS T2ON sc.S# = T2.S# AND T2.C# = 'k2'LEFT JOIN sc AS T3ON sc.S# = T3.S# AND T3.C# = 'k3'LEFT JOIN sc AS T4ON sc.S# = T4.S# AND T4.C# = 'k4'ORDER BY ISNULL(T1.score,0) + ISNULL(T2.score,0) + ISNULL(T3.score,0) + ISNULL(T4.score,0) DESC);23、统计列印各科成绩,各分数段人数:课程ID,课程名称,[100-85],[85-70],[70-60],[ <60]SELECT SC.C# as 课程ID, Cname as 课程名称,SUM(CASE WHEN score BETWEEN 85 AND 100 THEN 1 ELSE 0 END) AS[100 - 85],SUM(CASE WHEN score BETWEEN 70 AND 85 THEN 1 ELSE 0 END) AS [85 - 70],SUM(CASE WHEN score BETWEEN 60 AND 70 THEN 1 ELSE 0 END) AS [70 - 60],SUM(CASE WHEN score < 60 THEN 1 ELSE 0 END) AS [60 -]FROM SC,Coursewhere SC.C#=Course.C#GROUP BY SC.C#,Cname;24、查询学生平均成绩及其名次SELECT 1+(SELECT COUNT( distinct 平均成绩)FROM (SELECT S#,AVG(score) AS 平均成绩FROM SCGROUP BY S#) AS T1WHERE 平均成绩> T2.平均成绩) as 名次,S# as 学生学号,平均成绩FROM (SELECT S#,AVG(score) 平均成绩FROM SCGROUP BY S#) AS T2ORDER BY 平均成绩desc;25、查询各科成绩前三名的记录:(不考虑成绩并列情况)SELECT t1.S# as 学生ID,t1.C# as 课程ID,Score as 分数FROM SC t1WHERE score IN (SELECT TOP 3 scoreFROM SCWHERE t1.C#= C#ORDER BY score DESC)ORDER BY t1.C#;26、查询每门课程被选修的学生数select c#,count(S#) from sc group by C#;27、查询出只选修了一门课程的全部学生的学号和姓名select SC.S#,Student.Sname,count(C#) AS 选课数from SC ,Studentwhere SC.S#=Student.S# group by SC.S# ,Student.Sname having count(C#)=1;28、查询男生、女生人数Select count(Ssex) as 男生人数from Student group by Ssex having Ssex='男';Select count(Ssex) as 女生人数from Student group by Ssex having Ssex='女';29、查询姓“张”的学生名单SELECT Sname FROM Student WHERE Sname like '张%';30、查询同名同性学生名单,并统计同名人数select Sname,count(*) from Student group by Sname having count(*)>1;;31、1981年出生的学生名单(注:Student表中Sage列的类型是datetime)select Sname, CONVERT(char (11),DATEPART(year,Sage)) as agefrom studentwhere CONVERT(char(11),DATEPART(year,Sage))='1981';32、查询每门课程的平均成绩,结果按平均成绩升序排列,平均成绩相同时,按课程号降序排列Select C#,Avg(score) from SC group by C# order by Avg(score),C# DESC ;33、查询平均成绩大于85的所有学生的学号、姓名和平均成绩select Sname,SC.S# ,avg(score)from Student,SCwhere Student.S#=SC.S# group by SC.S#,Sname having avg(score)>85;34、查询课程名称为“数据库”,且分数低于60的学生姓名和分数Select Sname,isnull(score,0)from Student,SC,Coursewhere SC.S#=Student.S# and SC.C#=Course.C# and ame='数据库'and score <60;35、查询所有学生的选课情况;SELECT SC.S#,SC.C#,Sname,CnameFROM SC,Student,Coursewhere SC.S#=Student.S# and SC.C#=Course.C# ;36、查询任何一门课程成绩在70分以上的姓名、课程名称和分数;SELECT distinct student.S#,student.Sname,SC.C#,SC.scoreFROM student,ScWHERE SC.score>=70 AND SC.S#=student.S#;37、查询不及格的课程,并按课程号从大到小排列select c# from sc where scor e <60 order by C# ;38、查询课程编号为003且课程成绩在80分以上的学生的学号和姓名;select SC.S#,Student.Sname from SC,Student where SC.S#=Student.S# and Score>80 and C#='003';39、求选了课程的学生人数select count(*) from sc;40、查询选修“叶平”老师所授课程的学生中,成绩最高的学生姓名及其成绩select Student.Sname,scorefrom Student,SC,Course C,Teacherwhere Student.S#=SC.S# and SC.C#=C.C# and C.T#=Teacher.T# and Teacher.Tname='叶平' and SC.score=(select max(score)from SC where C#=C.C# );41、查询各个课程及相应的选修人数select count(*) from sc group by C#;42、查询不同课程成绩相同的学生的学号、课程号、学生成绩select distinct A.S#,B.score from SC A ,SC B where A.Score=B.Score and A.C# <>B.C# ;43、查询每门功成绩最好的前两名SELECT t1.S# as 学生ID,t1.C# as 课程ID,Score as 分数FROM SC t1WHERE score IN (SELECT TOP 2 scoreFROM SCWHERE t1.C#= C#ORDER BY score DESC)ORDER BY t1.C#;44、统计每门课程的学生选修人数(超过10人的课程才统计)。