SQL命令大全--中文翻译

SQL命令大全--中文翻译2009-05-24 13:25:39 浏览次数:0-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 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 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_limitsql_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 本篇文章来源于IT知识网/ 原文链接:/2009/0524/4963.html。

合集下载

SQL基本查询语句翻译

SQL基本查询语句翻译

select sno,sname from student从学生资料表中查询全体学生的学号、姓名select sname,sno,sdept from student从学生资料表中查询全体学生的姓名、学号和系别select * from student从学生资料表中查询全体学生的详细信息select sname,2006-sage from student从学生资料表中查询全体学生的姓名及其出生年月select sname,2006-sage as '出生年月' from student从学生资料表中查询全体学生的姓名及其出生年月select sname as'姓名',2006-sage as '出生年月' from student从学生资料表中查询全体学生的姓名及其出生年月select sname 姓名,2006-sage 出生年月from student从学生资料表中查询全体学生的姓名及其出生年月select distinct sno from student从学生资料表中查询所有不同的学号select sname from student where sdept='计算机系'从学生资料表中查询所在系为计算机系的学生姓名select sname,sage from student where sage<20从学生资料表中查询年龄在20岁以下的学生姓名及其年龄select sname,sdept,sage from student where sage between 20 and 23从学生资料表中查询年龄在20至23岁(包括20岁和23岁)之间的学生姓名、系别和年龄select sname,sdept,sage from studen t where sage>=20 and sage<=23从学生资料表中查询年龄在20至23岁(包括20岁和23岁)之间的学生姓名、系别和年龄select sname,sdept,sage from student where sage not between 20 and 23从学生资料表中查询年龄不在20至23岁之间的学生姓名、系别和年龄select sname,sdept,sage from student where sage<20 or sage>23从学生资料表中查询年龄年龄小于20岁或者大于23岁的学生姓名、系别和年龄select sname,ssex from student where sdept in ('信息系','数学系','计算机系')从学生资料表中查询信息系、数学系和计算机系学生的姓名和性别select sname,ssex from studen t where sdept='信息系' or sdept='数学系' or sdept='计算机系'从学生资料表中查询信息系或者数学系或者计算机系学生的姓名和性别select sname,ssex from student where sdept not in ('信息系','数学系','计算机系')从学生资料表中查询既不是信息系、数学系又不是计算机系的学生的姓名和性别select sname,ssex from student where sdept!='信息系' or sdept!='数学系' or sdept!='计算机系'从学生资料表中查询不是信息系或者不是数学系或者不是计算机系的学生的姓名和性别select sname,ssex from student where sdept!='信息系' and sdept!='数学系' and sdept!='计算机系'从学生资料表中查询既不是信息系、数学系又不是计算机系的学生的姓名和性别select * from student where sname like'张%'从学生资料表中查询所有姓张学生的详细信息select * from student where sname like'[张李刘]%'从学生资料表中查询所有姓张、李、刘的学生的详细信息select * from student where sname like'_[小大]%'从学生资料表中查询名字中第2个字为小或者大字的学生的详细信息select * from student where sname not like'刘%'从学生资料表中查询不姓刘的学生的详细信息select * from student where sno like'%[^2-6]'从学生资料表中查询学号不以2-6任意一个字符结尾的学生的详细信息select * from sc where grade is null从学生成绩表中查询无成绩的学生的详细信息select * from sc where grade is not null从学生成绩表中查询有成绩的学生的详细信息select * from student where sdept='计算机系' and sage<20从学生资料表中查询计算机系且年龄小于20岁的学生的详细信息select * from studen t order by sage从学生资料表中查询所有学生的详细信息,查询结果按年龄升序排列select * from studen t order by sage desc从学生资料表中查询所有学生的详细信息,查询结果按年龄降序排列select sno,grade from sc where cno='c02' order by grade desc从学生成绩表中查询课程号为c02的所有学生的学号和成绩,查询结果按成绩降序排列select * from student order by sdept,sage desc从学生资料表中查询所有学生的详细信息,查询结果按系别升序排列,同一系中的学生按年龄降序排列select count(*) from student从学生资料表中查询学生的总人数select count(distinct sno) from sc从学生成绩表中查询选修了课程的学生人数select sum(grade) from sc where sno='9512101'从学生成绩表中查询并计算学号为9512101的学生的总成绩select avg(grade) from sc where cno='c01'从学生成绩表中查询并计算课程号为c01的学生的平均成绩select max(grade),min(grade) from sc where cno='c01'从学生成绩表中查询课程号为c01的学生最高分数和最低分数select cno as 课程号,count(sno) as 选课人数from sc group by cno从学生成绩表中查询并计算各个课程号及相应的选课人数select sno 学号,count(*) 选课门数,avg(grade) 平均成绩from sc group by sno从学生成绩表中查询并计算各个学号及对应的选课门数并求平均成绩select sno from sc group by sno having count(*)>3从学生成绩表中查询选修了3门及以上课程的学生学号select sno,avg(grade),count(*) from sc group by sno having count(*)>=4从学生成绩表中查询选修了4门及以上的学生学号、平均成绩及课程数select * from studen t inner join sc on student.sno=sc.sno从学生资料表和成绩表中查询每个学生及其选修课程的情况select student.sno,sname,ssex,sage,sdept,cno,grade,xklb from student join sc on student.sno=sc.sno从学生资料表和成绩表中查询每个学生及其选修课程情况的学生学号、姓名、姓名、年龄、课程号、成绩和相关类别select sname,cno,grade from student join sc on s tudent.sno=sc.sno where sdept='计算机系'从学生资料表和成绩表中查询计算机系的每个学生及相应选修课程的学生姓名、课程号和成绩。

plsql用户指南与参考(中文翻译版)

plsql用户指南与参考(中文翻译版)

第一章PL/SQL一览一、理解PL/SQL的主要特性了解PL/SQL最好的方法就是从简单的实例入手。

下面的程序是用于处理一个网球拍订单的。

首先声明一个NUMBER类型的变量来存放现有的球拍数量。

然后从数据表inventory中把球拍的数量检索出来。

如果数量大于零,程序就会更新inventory表,并向purchase_record表插入一条购买记录,如果数量不大于零,程序会向purchase_record表插入一条脱销(out-of-stock)记录。

DECLAREqty_on_hand NUMBER(5);BEGINSELECT quantityINTO qty_on_handFROM inventoryWHERE product = 'TENNIS RACKET'FOR UPDATE OF quantity;IF qty_on_hand > 0 THEN-- check quantityUPDATE inventorySET quantity = quantity - 1WHERE product = 'TENNIS RACKET';INSERT INTO purchase_recordVALUES ('Tennis racket purchased', SYSDATE);ELSEINSERT INTO purchase_recordVALUES ('Out of tennis rackets', SYSDATE);END IF;COMMIT;END;在PL/SQL中,可以使用SQL语句来操作Oracle中的数据,并使用流程控制语句来处理数据。

我们还可以声明常量和变量,定义函数和过程并捕获运行时错误。

因此,PL/SQL是一种把SQL对数据操作的优势和过程化语言数据处理优势结合起来的语言。

1、块结构PL/SQL是一种块结构的语言,它的基本组成单元是一些逻辑块,而这些块又能嵌套任意数量子块。

SQL命令大全(可编辑修改word版)

SQL命令大全(可编辑修改word版)

下列语句部分是Mssql 语句,不可以在access 中使用。

SQL 分类:DDL 类型包括数据库、表的创建,修改,删除,声明—数据定义语言(CREATE,ALTER,DROP,DECLARE)DML 类型包括数据表中记录的查询,删除,修改,插入—数据操纵语言(SELECT,DELETE,UPDATE,INSERT)DCL 类型包括数据库用户赋权,废除用户访问权限,提交当前事务,中止当前事务—数据控制语言(GRANT,REVOKE,COMMIT,ROLLBACK)首先,简要介绍基础语句:1、说明:创建数据库CREATE DATABASE db1(db1 代表数据库表,可自命名)2、说明:删除数据库drop database db1(db1 代表数据库表,可自命名)3、说明:备份sql server--- 创建备份数据的deviceUSE masterEXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat'--- 开始备份BACKUP DATABASE pubs TO testBack4、说明:创建新表create table tb1(Id int not null primary key,name varchar,..)(tb1 为数据表名,ID 为字段,int 为数据类型整型,not null 为数据是否可为空,Primary Key 为主键设置,其中not null,primary key 为可选项,字段,数据类型自定义。

)根据已有的表创建新表:A:create table tab_new like tab_old (使用旧表创建新表)B:create table tab_new as select col1,col2… from tab_old definition only5、说明:删除新表:drop table tb16、说明:增加一个列:Alter table tabname add column col type注:列增加后将不能删除。

sql命令语句

sql命令语句

sql命令语句嘿,朋友!你知道 SQL 命令语句吗?这玩意儿可太重要啦!就好比是一把神奇的钥匙,能打开数据库那神秘宝库的大门。

比如说,当你想要从一个超级大的数据库里找出特定的信息,这时候 SQL 的 SELECT 语句就派上用场啦!“SELECT * FROM table_name”,就像你在茫茫人海中精准地找到你要找的那个人一样神奇!你能想象没有它该怎么办吗?还有啊,INSERT 语句,那简直就是给数据库添加新东西的魔法棒呀!“INSERT INTO table_name (column1, column2, column3) VALUES (value1, value2, value3)”,这不就像是给一个空房间里添置新家具嘛,一下子就让它丰富起来了。

UPDATE 语句呢,就像是给已有的东西做个小改造,让它更符合你的需求。

“UPDATE table_name SET column1 = value1 WHERE condition”,这多像给一件衣服换个扣子或者改个颜色呀!DELETE 语句,哎呀,这可有点厉害咯!它就像是把不需要的东西直接清理掉。

“DELETE FROM table_name WHERE condition”,这就像你清理房间时扔掉那些没用的杂物一样果断。

我之前和一个朋友一起做项目,他对 SQL 命令语句不太熟悉,结果在处理数据的时候那叫一个手忙脚乱啊!我就跟他说:“嘿,你得好好学学 SQL 命令语句呀,不然这工作可没法干啦!”他还不信,后来吃了不少苦头才意识到重要性。

SQL 命令语句真的是太实用啦!它是我们和数据库沟通的桥梁,没有它,我们怎么能在数据的海洋里畅游呢?所以呀,一定要好好掌握它,让它为我们的工作和生活带来便利!这就是我的观点,SQL 命令语句,不可或缺!。

SQL命令和经常使用语句大全【经典】

SQL命令和经常使用语句大全【经典】

SQL命令和经常使用语句大全【经典】学习SQL应明白的动态SQL语句大体语法1 、一般SQL语句能够用Exec执行eg: Select * from tableNameExec('select * from tableName')Exec sp_executesql N'select * from tableName' -- 请注意字符串前必然要加N2、字段名,表名,数据库名之类作为变量时,必需用动态SQLeg:declare @fname varchar(20)set @fname = 'FiledName'Select @fname from tableName -- 错误,可不能提示错误,但结果为固定值FiledName,并非所要。

Exec('select ' + @fname + ' from tableName') -- 请注意加号前后的单引号的边上加空格固然将字符串改成变量的形式也可declare @fname varchar(20)set @fname = 'FiledName' --设置字段名declare @s varchar(1000)set @s = 'select ' + @fname + ' from tableName'Exec(@s) -- 成功exec sp_executesql @s -- 此句会报错declare @s Nvarchar(1000) -- 注意此处改成nvarchar(1000) set @s = 'select ' + @fname + ' from tableName'Exec(@s) -- 成功exec sp_executesql @s -- 此句正确3、输出参数declare @num int,@sqls nvarchar(4000)set @sqls='select count(*) from tableName'exec(@sqls)--如何将exec执行结果放入变量中?declare @num int,@sqls nvarchar(4000)set @sqls='select @a=count(*) from tableName 'exec sp_executesql @sqls,N'@a int output',@num output select @num另外,若是想要在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 int select @x = 1 @y = 2 @z=3 if @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 BREAKdeclare @x int @y int @c intselect @x = 1 @y=1 while @x < 3beginprint @x --打印变量x 的值while @y < 3beginselect @c = 100*@x + @y print @c --打印变量c 的值select @y = @y + 1endselect @x = @x + 1 select @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 s tockname--------- 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 ---- 删除Stockna me的default约束***function(/*经常使用函数*/)***----统计函数----AVG --求平均值COUNT --统计数量MAX --求最大值MIN --求最小值SUM --求和--AVGuse panguselect avg(e_wage) as dept_avgWage from 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_timestamp data database databases datedatetime day day_hour day_minuteday_second dayofmonth dayofweek dayofyear dec 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 identified ignore 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_rows match mediumblob mediumtext mediumint middleint min_rows minute minute_second modify 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("别名") 获取统的计值,其它函数运用同上。

SQL命令大全

SQL命令大全

下列语句部分是Mssql语句,不可以在access中使用。

SQL分类:DDL类型包括数据库、表的创建,修改,删除,声明—数据定义语言(CREATE,ALTER,DROP,DECLARE)DML类型包括数据表中记录的查询,删除,修改,插入—数据操纵语言(SELECT,DELETE,UPDATE,INSERT)DCL类型包括数据库用户赋权,废除用户访问权限,提交当前事务,中止当前事务—数据控制语言(GRANT,REVOKE,COMMIT,ROLLBACK)首先,简要介绍基础语句:1、说明:创建数据库CREATE DATABASE db1(db1代表数据库表,可自命名)2、说明:删除数据库drop database db1(db1代表数据库表,可自命名)3、说明:备份sql server--- 创建备份数据的deviceUSE masterEXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat'--- 开始备份BACKUP DATABASE pubs TO testBack4、说明:创建新表create table tb1(Id int not null primary key,name varchar,..)(tb1为数据表名,ID为字段,int为数据类型整型,not null为数据是否可为空,Primary Key为主键设置,其中not null,primary key为可选项,字段,数据类型自定义。

)根据已有的表创建新表:A:create table tab_new like tab_old (使用旧表创建新表)B:create table tab_new as select col1,col2… from tab_old definition only5、说明:删除新表:drop table tb16、说明:增加一个列:Alter table tabname add column col type注:列增加后将不能删除。

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 &gt; @yprint ’x &gt; y’--打印字符串’x &gt; y’else if @y &gt; @zprint ’y &gt; z’else print ’z &gt; y’--CASEuse panguupdate employeeset e_wage =casewhen job_level = ’1’ then e_wage*1.08when job_level = ’2’ then e_wage*1.07when job_level = ’3’ then e_wage*1.06else e_wage*1.05end--WHILE CONTINUE BREAKdeclare @x int @y int @c intselect @x = 1 @y=1while @x &lt; 3beginprint @x --打印变量x 的值while @y &lt; 3beginselect @c = 100*@x + @yprint @c --打印变量c 的值select @y = @y + 1endselect @x = @x + 1select @y = 1end本文分页: 1 2 3 4 5--WAITFOR--例等待1 小时2 分零3 秒后才执行SELECT 语句waitfor delay ’01:02:03’select * from employee--例等到晚上11 点零8 分后才执行SELECT 语句waitfor ti me ’23:08:00’select * from employee ***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 &lt; 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 table2***insert***insert into table_name (Stock_name,Stock_number) value ("xxx","xxxx")value (select Stockname , Stocknumber fromStock_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约束本文分页: 1 2 3 4 5***function(/*常用函数*/)*** ----统计函数----A VG --求平均值COUNT --统计数目MAX --求最大值MIN --求最小值SUM --求和--A VGuse 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()函数返回总体标准差--V AR()--V AR()函数返回表达式中所有值的统计变异数--V ARP()--V ARP()函数返回总体变异数----算术函数----/***三角函数***/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) --返回&gt;=表达式的最小整数返回的数据类型与表达式相同可为--INTEGER/MONEY/REAL/FLOAT 类型FLOOR(numeric_expression) --返回&lt;=表达式的最小整数返回的数据类型与表达式相同可为--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 函数返回值完全相同本文分页: 1 2 3 4 5QUOTENAME() --函数返回被特定字符括起来的字符串/*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() (&lt;expression&gt; AS &lt;data_ type&gt;[ length ]) CONVERT() 函数语法如下CONVERT() (&lt;data_ type&gt;[ length ], &lt;expression&gt; [, 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(&lt;datepart&gt; ,&lt;number&gt; ,&lt;date&gt;)--函数返回指定日期date 加上指定的额外日期间隔number 产生的新日期DATEDIFF(&lt;datepart&gt; ,&lt;number&gt; ,&lt;date&gt;)--函数返回两个指定日期在datepart 方面的不同之处DATENAME(&lt;datepart&gt; , &lt;date&gt;) --函数以字符串的形式返回日期的指定部分DATEPART(&lt;datepart&gt; , &lt;date&gt;) --函数以整数值的形式返回日期的指定部分GETDATE() --函数以DATETIME 的缺省格式返回系统当前的日期和时间----系统函数----APP_NAME() --函数返回当前执行的应用程序的名称COALESCE() --函数返回众多表达式中第一个非NULL 表达式的值COL_LENGTH(&lt;’table_name’&gt;, &lt;’column_name’&gt;) --函数返回表中指定字段的长度值COL_NAME(&lt;table_id&gt;, &lt;column_id&gt;) --函数返回表中指定字段的名称即列名DATALENGTH() --函数返回数据表达式的数据的实际长度DB_ID([’database_name’]) --函数返回数据库的编号DB_NAME(database_id) --函数返回数据库的名称HOST_ID() --函数返回服务器端计算机的名称HOST_NAME() --函数返回服务器端计算机的名称IDENTITY(&lt;data_type&gt;[, seed increment]) [AScolumn_name])--IDENTITY() 函数只在SELECT INTO 语句中使用用于插入一个identity column列到新表中/*select identity(int, 1, 1) as column_nameinto newtablefrom oldtable*/ISDATE() --函数判断所给定的表达式是否为合理日期ISNULL(&lt;check_expression&gt;, &lt;replacement_value&gt;) --函数将表达式中的NULL 值用指定值替换ISNUMERIC() --函数判断所给定的表达式是否为合理的数值NEWID() --函数返回一个UNIQUEIDENTIFIER 类型的数值NULLIF(&lt;expression1&gt;, &lt;expression2&gt;)--NULLIF 函数在expression1 与expression2 相等时返回NULL 值若不相等时则返回expression1 的值本文分页: 1 2 3 4 5sql中的保留字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 identified ignore 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_rows match mediumblob mediumtext mediumint middleint min_rows minute minute_second modify month monthname myisam natural numeric no notnull on optimize optionoptionally or order outeroutfile pack_keys partial password precision primary procedure process processlist 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_updatesql_select_limitsql_small_result sql_big_result sql_warnings straight_join starting 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本文分页: 1 2 3 4 5。

SQL数据库基本操作命令

SQL数据库基本操作命令SQL是一种用于管理和操作关系型数据库的语言,具有丰富的操作命令。

以下是SQL数据库的基本操作命令,包括创建数据库、创建表、插入数据、查询数据、更新数据和删除数据等。

1.创建数据库命令CREATE DATABASE database_name; -- 创建一个新的数据库USE database_name; -- 使用指定的数据库2.创建表命令CREATE TABLE table_namecolumn1 datatype constraint,column2 datatype constraint,...;--创建一个新的表3.插入数据命令INSERT INTO table_name (column1, column2, ...)VALUES (value1, value2, ...); -- 向表中插入一条记录4.查询数据命令SELECT column1, column2, ...FROM table_name; -- 查询表中的所有记录SELECT column1, column2, ...FROM table_nameWHERE condition; -- 查询满足条件的记录SELECT DISTINCT column1, column2, ...FROM table_name; -- 查询不重复的记录SELECT column_name(s)FROM table1INNER JOIN table2 ON table1.column_name = table2.column_name; -- 连接两个表并查询指定列SELECT column_name(s)FROM table_nameORDER BY column_name ASC,DESC; -- 按列的升序或降序对查询结果进行排序5.更新数据命令UPDATE table_nameSET column1 = value1, column2 = value2, ...WHERE condition; -- 更新表中满足条件的记录6.删除数据命令DELETE FROM table_nameWHERE condition; -- 删除表中满足条件的记录TRUNCATE TABLE table_name; -- 删除表中的所有记录DROP TABLE table_name; -- 删除表7.其他操作命令ALTER TABLE table_nameADD column_name datatype; -- 向表中添加新的列ALTER TABLE table_nameDROP COLUMN column_name; -- 从表中删除指定的列ALTER TABLE table_nameMODIFY COLUMN column_name datatype; -- 修改表中指定列的数据类型ALTER TABLE table_nameRENAME TO new_table_name; -- 修改表名以上是SQL数据库的基本操作命令,通过这些命令可以管理与操作关系型数据库。

SQL数据库外文翻译

Working with DatabasesThis chapter describes how to use SQL statements in embedded applications to control databases. There are three database statements that set up and open databases for access: SET DATABASE declares a database handle, associates the handle with an actual database file, and optionally assigns operational parameters for the database.SET NAMES optionally specifies the character set a client application uses for CHAR, VARCHAR, and text Blob data. The server uses this information totransli terate from a database’s default character set to the client’s character set on SELECT operations, and to transliterate from a client application’s character set to the database character set on INSERT and UPDATE operations.g CONNECT opens a database, allocates system resources for it, and optionally assigns operational parameters for the database.All databases must be closed before a program ends. A database can be closed by using DISCONNECT, or by appending the RELEASE option to the final COMMIT or ROLLBACK in a program. Declaring a databaseBefore a database can be opened and used in a program, it must first be declared with SET DATABASE to:CHAPTER 3 WORKING WITH DATABASES. Establish a database handle. Associate the database handle with a database file stored on a local or remote node.A database handle is a unique, abbreviated alias for an actual database name. Database handles are used in subsequent CONNECT, COMMIT RELEASE, and ROLLBACK RELEASE statements to specify which databases they should affect. Except in dynamic SQL (DSQL) applications, database handles can also be used inside transaction blocks to qualify, or differentiate, table names when two or more open databases contain identically named tables.Each database handle must be unique among all variables used in a program. Database handles cannot duplicate host-language reserved words, and cannot be InterBase reserved words.The following statement illustrates a simple database declaration:EXEC SQLSET DATABASE DB1 = ’employee.gdb’;This database declaration identifies the database file, employee.gdb, as a database the program uses, and assigns the database a handle, or alias, DB1.If a program runs in a directory different from the directory that contains the database file, then the file name specification in SET DATABASE must include a full path name, too. For example, the following SET DATABASE declaration specifies the full path to employee.gdb:EXEC SQLSET DATABASE DB1 = ’/interbase/examples/employee.gdb’;If a program and a database file it uses reside on different hosts, then the file name specification must also include a host name. The following declaration illustrates how a Unix host name is included as part of the database file specification on a TCP/IP network:EXEC SQLSET DATABASE DB1 = ’jupiter:/usr/interbase/examples/employee.gdb’;On a Windows network that uses the Netbeui protocol, specify the path as follows: EXEC SQLSET DATABASE DB1 = ’//venus/C:/Interbase/examples/employee.gdb’; DECLARING A DATABASEEMBEDDED SQL GUIDE 37Declaring multiple databasesAn SQL program, but not a DSQL program, can access multiple databases at the same time. In multi-database programs, database handles are required. A handle is used to:1. Reference individual databases in a multi-database transaction.2. Qualify table names.3. Specify databases to open in CONNECT statements.Indicate databases to close with DISCONNECT, COMMIT RELEASE, and ROLLBACK RELEASE.DSQL programs can access only a single database at a time, so database handle use is restricted to connecting to and disconnecting from a database.In multi-database programs, each database must be declared in a separate SET DATABASE statement. For example, the following code contains two SET DATABASE statements:. . .EXEC SQLSET DATABASE DB2 = ’employee2.gdb’;EXEC SQLSET DATABASE DB1 = ’employee.gdb’;. . .4Using handles for table namesWhen the same table name occurs in more than one simultaneously accessed database, a database handle must be used to differentiate one table name from another. The database handle is used as a prefix to table names, and takes the formhandle.table.For example, in the following code, the database handles, TEST and EMP, are used to distinguish between two tables, each named EMPLOYEE:. . .EXEC SQLDECLARE IDMATCH CURSOR FORSELECT TESTNO INTO :matchid FROM TEST.EMPLOYEEWHERE TESTNO > 100;EXEC SQLDECLARE EIDMATCH CURSOR FORSELECT EMPNO INTO :empid FROM EMP.EMPLOYEEWHERE EMPNO = :matchid;. . .CHAPTER 3 WORKING WITH DATABASES38 INTERBASE 6IMPORTANTThis use of database handles applies only to embedded SQL applications. DSQL applications cannot access multiple databases simultaneously.4Using handles with operationsIn multi-database programs, database handles must be specified in CONNECT statements to identify which databases among several to open and prepare for use in subsequent transactions.Database handles can also be used with DISCONNECT, COMMIT RELEASE, and ROLLBACKRELEASE to specify a subset of open databases to close.To open and prepare a database w ith CONNECT, see “Opening a database” on page 41.To close a database with DISCONNECT, COMMIT RELEASE, or ROLLBACK RELEASE, see“Closing a database” on page 49. To learn more about using database handles in transactions, see “Accessing an open database” on p age 48.Preprocessing and run time databasesNormally, each SET DATABASE statement specifies a single database file to associate with a handle. When a program is preprocessed, gpre uses the specified file to validate the program’s table and column referenc es. Later, when a user runs the program, the same database file is accessed. Different databases can be specified for preprocessing and run time when necessary.4Using the COMPILETIME clause A program can be designed to run against any one of several identically structured databases. In other cases, the actual database that a program will use at runtime is not available when a program is preprocessed and compiled. In such cases, SET DATABASE can include a COMPILETIME clause to specify a database for gpre to test against during preprocessing. For example, the following SET DATABASE statement declares that employee.gdb is to be used by gpre during preprocessing: EXEC SQLSET DATABASE EMP = COMPILETIME ’employee.gdb’;IMPORTANTThe file specification that follows the COMPILETIME keyword must always be a hard-coded, quoted string.DECLARING A DATABASEEMBEDDED SQL GUIDE 39When SET DATABASE uses the COMPILETIME clause, but no RUNTIME clause, and does not specify a different database file specification in a subsequent CONNECT statement, the same database file is used both for preprocessing and run time. To specify different preprocessing and runtime databases with SET DATABASE, use both the COMPILETIME andRUNTIME clauses.4Using the RUNTIME clauseWhen a database file is specified for use during preprocessing, SET DATABASE can specify a different database to use at run time by including the RUNTIME keyword and a runtime file specification:EXEC SQLSET DATABASE EMP = COMPILETIME ’employee.gdb’RUNTIME ’employee2.gdb’;The file specification that follows the RUNTIME keyword can be either ahard-coded, quoted string, or a host-language variable. For example, the following C code fragment prompts the user for a database name, and stores the name in a variable that is used later in SET DATABASE:. . .char db_name[125];. . .printf("Enter the desired database name, including node and path):\n");gets(db_name);EXEC SQLSET DATABASE EMP = COMPILETIME ’employee.gdb’ RUNTIME : db_name; . . .Note host-language variables in SET DATABASE must be preceded, as always, by a colon.Controlling SET DATABASE scopeBy default, SET DATABASE creates a handle that is global to all modules in an application.A global handle is one that may be referenced in all host-language modules comprising the program. SET DATABASE provides two optional keywords to change the scope of a declaration:g STATIC limits declaration scope to the module containing the SET DATABASE statement. No other program modules can see or use a database handle declared STATIC.CHAPTER 3 WORKING WITH DATABASES40 INTERBASE 6EXTERN notifies gpre that a SET DATABASE statement in a module duplicates a globally-declared database in another module. If the EXTERN keyword is used, then another module must contain the actual SET DATABASE statement, or an error occurs during compilation.The STATIC keyword is used in a multi-module program to restrict database handle access to the single module where it is declared. The following example illustrates the use of theSTATIC keyword:EXEC SQLSET DATABASE EMP = STATIC ’employee.gdb’;The EXTERN keyword is used in a multi-module program to signal that SET DATABASE in one module is not an actual declaration, but refers to a declaration made in a different module. Gpre uses this information during preprocessing. The following example illustrates the use of the EXTERN keyword:EXEC SQLSET DATABASE EMP = EXTERN ’employee.gdb’;If an application contains an EXTERN reference, then when it is used at run time, the actual SET DATABASE declaration must be processed first, and the database connected before other modules can access it.A single SET DATABASE statement can contain either the STATIC or EXTERN keyword, but not both. A scope declaration in SET DATABASE applies to both COMPILETIME and RUNTIME databases.Specifying a connection character setWhen a client application connects to a database, it may have its own character set requirements. The server providing database access to the client does not know about these requirements unless the client specifies them. The client application specifies its character set requirement using the SET NAMES statement before it connects to the database.SET NAMES specifies the character set the server should use when translating data from the database to the client application. Similarly, when the client sends data to the database, the server translates the data from the client’s character set to the database’s default character set (or the character set for an individual column if it differs from the databas e’s default character set). For example, the following statements specify that the client is using the DOS437 character set, then connect to the database:EXEC SQLOPENING A DATABASEEMBEDDED SQL GUIDE 41SET NAMES DOS437;EXEC SQLCONNECT ’europe.gdb’ USER ’JAMES’ PASSWORD ’U4EEAH’;For more information about character sets, see the Data Definition Guide. For the complete syntax of SET NAMES and CONNECT, see the Language Reference. Opening a databaseAfter a database is declared, it must be attached with a CONNECT statement before it can be used. CONNECT:1. Allocates system resources for the database.2. Determines if the database file is local, residing on the same host where the application itself is running, or remote, residing on a different host.3. Opens the database and examines it to make sure it is valid.InterBase provides transparent access to all databases, whether local or remote. If the database structure is invalid, the on-disk structure (ODS) number does not correspond to the one required by InterBase, or if the database is corrupt, InterBase reports an error, and permits no further access. Optionally, CONNECT can be used to specify:4. A user name and password combination that is checked against the server’s security database before allowing the connect to succeed. User names can be up to 31 characters.Passwords are restricted to 8 characters.5. An SQL role name that the user adopts on connection to the database, provided that the user has previously been granted membership in the role. Regardless of role memberships granted, the user belongs to no role unless specified with this ROLE clause.The client can specify at most one role per connection, and cannot switch roles except by reconnecting.6. The size of the database buffer cache to allocate to the application when the default cache size is inappropriate.Using simple CONNECT statementsIn its simplest form, CONNECT requires one or more database parameters, each specifying the name of a database to open. The name of the database can be a: Database handle declared in a previous SET DATABASE statement.CHAPTER 3 WORKING WITH DATABASES42 INTERBASE 61. Host-language variable.2. Hard-coded file name.4Using a database handleIf a program uses SET DATABASE to provide database handles, those handles should be used in subsequent CONNECT statements instead of hard-coded names. For example,. . .EXEC SQLSET DATABASE DB1 = ’employee.gdb’;EXEC SQLSET DATABASE DB2 = ’employee2.gdb’;EXEC SQLCONNECT DB1;EXEC SQLCONNECT DB2;. . .There are several advantages to using a database handle with CONNECT:1. Long file specifications can be replaced by shorter, mnemonic handles.2. Handles can be used to qualify table names in multi-database transactions. DSQL applications do not support multi-database transactions.3. Handles can be reassigned to other databases as needed.4. The number of database cache buffers can be specified as an additional CONNECT parameter.For more information about setting the number of database cache buffers, see “Setting d atabase cache buffers” on page 47. 4Using strings or host-language variables Instead of using a database handle, CONNECT can use a database name supplied at run time. The database name can be supplied as either a host-language variable or a hard-coded, quoted string.The following C code demonstrates how a program accessing only a single database might implement CONNECT using a file name solicited from a user at run time:. . .char fname[125];. . .printf(’Enter the desired database name, including nodeand path):\n’);OPENING A DATABASEEMBEDDED SQL GUIDE 43gets(fname);. . .EXEC SQLCONNECT :fname;. . .TipThis technique is especially useful for programs that are designed to work with many identically structured databases, one at a time, such as CAD/CAM or architectural databases.MULTIPLE DATABASE IMPLEMENTATIONTo use a database specified by the user as a host-language variable in a CONNECT statement in multi-database programs, follow these steps:1. Declare a database handle using the following SET DATABASE syntax:EXEC SQLSET DATABASE handle = COMPILETIME ’ dbname’;Here, handle is a hard-coded database handle supplied by the programmer, dbnameis a quoted, hard-coded database name used by gpre during preprocessing.2. Prompt the user for a database to open.3. Store the database name entered by the user in a host-language variable.4. Use the handle to open the database, associating the host-language variable with the handle using the following CONNECT syntax:EXEC SQLCONNECT : variable AS handle;The following C code illustrates these steps:. . .char fname[125];. . .EXEC SQLSET DATABASE DB1 = ’employee.gdb’;printf("Enter the desired database name, including nodeand path):\n");gets(fname);EXEC SQLCONNECT :fname AS DB1;. . .CHAPTER 3 WORKING WITH DATABASES44 INTERBASE 6In this example, SET DATABASE provides a hard-coded database file name for preprocessing with gpre. When a user runs the program, the database specified in the variable, fname, is used instead. 4Using a hard-coded database namesIN SINGE-DATABASE PROGRAMSIn a single-database program that omits SET DATABASE, CONNECT must contain a hard-coded, quoted file name in the following format:EXEC SQLCONNECT ’[ host[ path]] filename’; host is required only if a program and a dat abase file it uses reside on different nodes.Similarly, path is required only if the database file does not reside in the current working directory. For example, the following CONNECT statement contains ahard-coded file name that includes both a Unix host name and a path name:EXEC SQLCONNECT ’valdez:usr/interbase/examples/employee.gdb’;Note Host syntax is specific to each server platform.IMPORTANT A program that accesses multiple databases cannot use this form of CONNECT.IN MULTI-DATABASE PROGRAMSA program that accesses multiple databases must declare handles for each of them in separate SET DATABASE statements. These handles must be used in subsequent CONNECT statements to identify specific databases to open:. . .EXEC SQLSET DATABASE DB1 = ’employee.gdb’;EXEC SQLSET DATABASE DB2 = ’employee2.gdb’;EXEC SQLCONNECT DB1;EXEC SQLCONNECT DB2;. . .Later, when the program closes these databases, the database handles are no longer in use. These handles can be reassigned to other databases by hard-coding a file name in a subsequent CONNECT statement. For example,OPENING A DATABASEEMBEDDED SQL GUIDE 45. . .EXEC SQLDISCONNECT DB1, DB2;EXEC SQLCONNECT ’project.gdb’ AS DB1;. . .Additional CONNECT syntaxCONNECT supports several formats for opening databases to provide programming flexibility. The following table outlines each possible syntax, provides descriptions and examples, and indicates whether CONNECT can be used in programs that access single or multiple databases:For a complete discussion of CONNECT syntax and its uses, see the Language Reference.Syntax Description ExampleSingle accessMultiple accessCONNECT ‘dbfile’; Opens a single, hard-coded database file, dbfile.EXEC SQLCONNECT ‘employee.gdb’;Yes NoCONNECT handle; Opens the database file associated with a previously declared database handle. This is the preferred CONNECT syntax.EXEC SQLCONNECT EMP;Yes YesCONNECT ‘dbfile’ AS handle;Opens a hard-coded database file, dbfile, and assigns a previously declared database handle to it.EXEC SQLCONNECT ‘employee.gdb’AS EMP;Yes Yes CONNECT :varname AS handle;Opens the database file stored in the host-language variable, varname, and assigns a previously declared database handle to it.EXEC SQL CONNECT :fname AS EMP;Yes YesTABLE 3.1 CONNECT syntax summaryCHAPTER 3 WORKING WITH DATABASES46 INTERBASE 6Attaching to multiple databasesCONNECT can attach to multiple databases. To open all databases specified in previous SETDATABASE statements, use either of the following CONNECT syntax options: EXEC SQLCONNECT ALL;EXEC SQLCONNECT DEFAULT;CONNECT can also attach to a specified list of databases. Separate each database request from others with commas. For example, the following statement opens two databases specified by their handles:EXEC SQLCONNECT DB1, DB2;The next statement opens two hard-coded database files and also assigns them to previously declared handles:EXEC SQLCONNECT ’employee.gdb’ AS DB1, ’employee2.gdb’ AS DB2;Tip Opening multiple databases with a single CONNECT is most effective when a program’s database access is simple and clear. In complex programs that open and close several databases, that substitute database names with host-language variables, or that assign multiple handles to the same database, use separate CONNECT statements to make program code easier to read, debug, and modify.Handling CONNECT errors. The WHENEVER statement should be used to trap and handle runtime errors that occur during database declaration. The following C code fragment illustrates an error-handling routine that displays error messages and ends the program in an orderly fashion:. . .EXEC SQLWHENEVER SQLERRORGOTO error_exit;. . .OPENING A DATABASEEMBEDDED SQL GUIDE 47:error_exitisc_print_sqlerr(sqlcode, status_vector);EXEC SQLDISCONNECT ALL;exit(1);. . .For a complete discussion of SQL error handling, see Chapter 12, “Error Handling and Recovery.”数据库的工作这章描述怎样使用在嵌入式应用过程中的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.08when job_level = '2' then e_wage*1.07when job_level = '3' then e_wage*1.06else e_wage*1.05end--WHILE CONTINUE BREAKdeclare @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 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 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())运行结果如下------------------------------ ----------------日期函数----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 的值--------------------------------------------------------------------------------。

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