SQL Server语法入门

1、说明:增加、删除一个列
Alter table tablename add columnName col type
alter table tablename drop columnName column_b
2.添加删除主键
alter table tableName add constraint PK_Name primary key(Name)
alter table tableName drop constraint PK_Name
3、说明:创建视图、删除视图
create view viewname as select statement
drop view viewname
4、说明:几个简单的基本的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 table1

5.A: UNION 运算符
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL)不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。
B: EXCEPT 运算符
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。
C: INTERSECT运算符
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当ALL随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。

6.说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用)
法一:select * into b from a where 1<>1(仅用于SQlServer)
法二:select top 0 * into b from a

  1. 说明:跨数据库之间表的拷贝
    eg:insert into stuDB.dbo.amount select * from 北风贸易.dbo.amount where nickname in ('1','2')

8、说明:在线视图查询(表名1:a )
select * from (SELECT a,b,c FROM a) T where t.a > 1;

9、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括
select * from table1 where time between time1 and time2
select a,b,c, from table1 where a not between 数值1 and 数值2

10、说明:in 的使用方法
select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)

11、说明:日程安排提前五分钟提醒
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5

12.按姓氏笔画排序:
Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as //从少到多

13、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.)
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)

14、说明:随机取出10条数据
select top 10 * from tablename order by newid()

15、说明:随机选择记录
select newid()

16、说明:删除重复记录
1),delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)(有待考证)
2),select distinct * into temp from tablename
delete from tablename
insert into tablename select * from temp

查询一个数据库里有多少张表
select COUNT(1) from sysobjects where type='U'
select COUNT(1) from information_schema.tables where TABLE_TYPE='BASE TABLE'

17、说明:列出数据库里所有的表名
select name from sysobjects where type='U' // U代表用户

18、说明:列出表里的所有的列名
select name from syscolumns where id=object_id('表名')
select name from syscolumns where id in (select id from sysobjects where type = 'u' and name = '表名')
两种方式的效果相同
查询表结构
SELECT col.name AS columnName ,
t.name AS dataType,
ISNULL(ep.[value], '') AS columnComment ,
CASE WHEN EXISTS (
SELECT 1 FROM dbo.sysindexes si
INNER JOIN dbo.sysindexkeys sik ON si.id = sik.id AND si.indid = sik.indid
INNER JOIN dbo.syscolumns sc ON sc.id = sik.id AND sc.colid = sik.colid
INNER JOIN dbo.sysobjects so ON so.name = si.name AND so.xtype = 'PK'
WHERE sc.id = col.id AND sc.colid = col.colid ) THEN 'PRI'
ELSE ''
END AS columnKey,
CASE WHEN COLUMNPROPERTY(col.id, col.name, 'IsIdentity') = 1 THEN 'auto_increment' ELSE '' END AS extra
FROM dbo.syscolumns col
LEFT JOIN dbo.systypes t ON col.xtype = t.xusertype
inner JOIN dbo.sysobjects obj ON col.id = obj.id AND obj.xtype = 'U' AND obj.status >= 0
LEFT JOIN dbo.syscomments comm ON col.cdefault = comm.id
LEFT JOIN sys.extended_properties ep ON col.id = ep.major_id AND col.colid = ep.minor_id AND ep.name = 'MS_Description'
LEFT JOIN sys.extended_properties epTwo ON obj.id = epTwo.major_id AND epTwo.minor_id = 0 AND epTwo.name = 'MS_Description'
WHERE obj.name = 'InspectionPlanList'--表名
ORDER BY col.colorder ;

19:查看与某一个表相关的视图、存储过程、函数
select a.* from sysobjects a, syscomments b where a.id = b.id and b.text like '%表名%'

20:查看当前数据库中所有存储过程
select name as 存储过程名称 from sysobjects where xtype='P'

21:查询用户创建的所有数据库
select * from master..sysdatabases D where sid not in(select sid from master..syslogins where name='sa')
或者
select dbid, name AS DB_NAME from master..sysdatabases where sid <> 0x01

22:查询某一个表的字段和数据类型
select column_name,data_type from information_schema.columns
where table_name = '表名'

eg:写一个SQL语句, 找出表的第31到第40个记录。
select top 10 recid from A where recid not in(select top 30 recid from A)

23.字符串函数 长度与分析用
1,datalength(Char_expr) 返回字符串包含字符数,但不包含后面的空格
2,substring(expression,start,length) 取子串,字符串的下标是从“1”,start为起始位置,length为字符串长度,实际应用中以len(expression)取得其长度
3,right(char_expr,int_expr) 返回字符串右边第int_expr个字符,还用left于之相反
4,isnull( check_expression,replacement_value)如果check_expression為空,則返回replacement_value的值,不為空,就返回check_expression字符操作类

24.写SQL进行排序的时候我们可能按照username进行排序,我们可能按照名字的拼音、比划及偏旁部首进行排序,Oracle刚好提供了这样的一个函数nlssort()
NLSSORT(),用来进行语言排序
拼音
SELECT * FROM TEAM ORDER BY NLSSORT(排序字段名,'NLS_SORT = SCHINESE_PINYIN_M')
笔划
SELECT * FROM TEAM ORDER BY NLSSORT(排序字段名,'NLS_SORT = SCHINESE_STROKE_M')
部首
SELECT * FROM TEAM ORDER BY NLSSORT(排序字段名,'NLS_SORT = SCHINESE_RADICAL_M')

25.产生随机数,三种方式都可以
select dbms_random.value from dual
select dbms_random.random from dual
select sys_guid() from dual
26.select to_date('2016/12/15 9:23:48','yyyy/MM/dd hh24:mi:ss ') from dual
27.http://blog.sina.com.cn/s/blog_4ce36a780101b1rl.html oracle时间转换及获取
28.Oracle获取表结构
select COLUMN_NAME,DATA_TYPE,DATA_LENGTH from user_tab_cols where table_name='表名' (表名字母必须全部大写)
27.文字转换,时间转为短日期格式
select xbm=
case
when xbm='1' then '男'
when xbm='2' then '女'
end,
csrq=CONVERT(varchar(12),csrq,111)
from student
28.sql Server中和Oracle的RowNum作用相同
Row_ID=ROW_NUMBER() OVER(ORDER BY (SELECT 1))
row_number() over(order by Displayname) as RowNum
29.标量的使用
declare @count int
select top 100 @count=COUNT(*) from RenYuan_BaseInfo
select @count
30.排名
SELECT 姓名,成绩,
ROW_NUMBER() OVER(ORDER BY 成绩 DESC) AS [ROW_NUMBER],
RANK() OVER(ORDER BY 成绩 DESC) AS [RANK],
DENSE_RANK() OVER(ORDER BY 成绩 DESC) AS [DENSE_RANK],
NTILE(6) OVER(ORDER BY 成绩 DESC) AS [NTILE]
FROM @table

31.Oracle时间比较
SELECT * FROM SR_Punish_CaseInfo WHERE to_char(registerdate,'yyyy-mm-dd') = '2016-09-09'
select * from SR_Punish_CaseInfo WHERE trunc(registerdate)=to_date('2016-09-09','yyyy-mm-dd') 、
32.行转列
select WM_CONCAT(to_char(itemtext ||'='|| itemvalue)) as aa from code_items where codeid= (select codeid from code_main where codename='听证会方式' )
33.字符串拼接
select cheifsupengineer || '的结构是:'|| structtype 介绍 from zljd_yanshoutz
34.Oracle时间
to_date('2013-10-10 13:13:13','yyyy-mm-dd hh24:mi:ss') 长日期
to_date('2011/01/01','yyyy/mm/dd') 端日期
sysdate 系统日期
35. 分组统计数量
select AddUserName,sum(case LowProtectionType when '残疾' then 1 else 0 end) '残疾',sum(case LowProtectionType when '受灾' then 1 else 0 end) '受灾',sum(case LowProtectionType when '大病' then 1 else 0 end) '大病' FROM LowProtectionInfo group by AddUserName

36.比较A,B表数据是否相等
if (select checksum_agg(binary_checksum(*)) from A)

(select checksum_agg(binary_checksum(*)) from B)
print '相等'c
print '不相等'
37.获取当天的数据
select * from Art_News_JRZB where Convert(varchar(100),ZBDate,23)=Convert(varchar(100),GETDATE(),23)
38.Oracle排序,AuditStatus是条件,后面的0,1是排列顺序
http://blog.csdn.net/weeknd/article/details/71157044 decode函数的使用
string OrderBy = " decode(Status,'2',0),decode(Status,'3',1),Row_id desc";
39.NVL(eExpression1, eExpression2)
如果 eExpression1 的计算结果为 null 值,则 NVL( ) 返回 eExpression2。如果 eExpression1 的计算结果不是 null 值,则返回 eExpression1。eExpression1 和 eExpression2 可以是任意一种数据类型。如果 eExpression1 与 eExpression2 的结果皆为 null 值,则 NVL( ) 返回 .NULL.。
40.执行SQL语句块,eg2带有参数
DECLARE @sid NVARCHAR(20)
SET @sid='84121'
DECLARE @selectSQL NVARCHAR(3000)
SET @selectSQL='SELECT * FROM dbo.aa WHERE sid LIKE ''%'+@sid+'%'''
PRINT @selectSQL
exec sp_executesql @selectSQL

eg2:DECLARE @district NVARCHAR(20)
SET @District='三水燃气'
DECLARE @SQL NVARCHAR(3000)
SET @SQL='SELECT ObjectID,SID,District,{0} FROM dbo.aa WHERE District = ''{1}'''
SET @SQL= REPLACE(@SQL,'{0}','thick')
SET @SQL= REPLACE(@SQL,'{1}',@District)
PRINT @SQL
exec sp_executesql @SQL
41.统计数据库中每张表的大小
create table tmp
(
name varchar(50),
rowscount int,
reserved varchar(50),
data varchar(50),
index_size varchar(50),
unused varchar(50)
);
insert tmp(name, rowscount, reserved, data, index_size, unused)
exec sp_MSforeachtable @command1="sp_spaceused '?'";
select * from tmp where name <> 'tmp' order by name
drop table tmp ;

posted @ 2018-11-23 15:11  Hello,Code  阅读(683)  评论(0编辑  收藏  举报