sql总结

数据库与SQL基础教程

Ø 基本数据类型 
精确数字类型 
类型	描述
bigint	bigint 数据类型用于整数值可能超过 int 数据类型支持范围的情况,范围:-2^63 到 2^63-1,
存储空间8字节
int	整数数据类型,范围在-2^31 到 2^31-1,存储空间4字节
smallint	整数,范围在-2^15 到 2^15-1,存储空间2字节
tinyint	范围在0 到 255,存储空间1字节
bit	可以取值为 1、0 或 NULL 的整数数据类型,每8个bit占一个字节,16bit就2个字节,24bit就3个字节
decimal	带固定精度和小数位数的数值数据类型,有效值从 - 10^38 +1 到 10^38 - 1
numeric	同上
money	货币或货币值的数据类型,范围在-922,337,203,685,477.5808 到 922,337,203,685,477.5807
smallmoney	货币类型,-214,748.3648 到 214,748.3647

近似数字类型 
类型	描述
float	表示浮点数值数据的大致数值数据类型。浮点数据为近似值;范围-1.79E + 308 至 -2.23E - 308、0 
以及 2.23E - 308 至 1.79E + 308
real	real 的 SQL-92 同义词为 float(24),范围在-3.40E + 38 至 -1.18E - 38、0 以及 1.18E – 38
 至 3.40E + 38

日期时间类型 
类型	描述
datetime	表示某天的日期和时间的数据类型,范围在1753 年 1 月 1 日到 9999 年 12 月 31 日
smalldatetime	范围在1900 年 1 月 1 日到 2079 年 6 月 6 日
  
字符串类型 
类型	描述
char	固定长度或可变长度的字符数据类型,范围在范围为 1 至 8,000字节
text	最大长度为 2^31-1
varchar	固定长度或可变长度的字符数据类型,最大存储大小是 2^31-1 个字节

Unicode字符串类型 
类型	描述
nchar	字符数据类型,长度固定,在必须在 1 到 4,000 之间
nvarchar	可变长度 Unicode 字符数据。最大存储大小为 2^31-1 字节
ntext	长度可变的 Unicode 数据,最大长度为 2^30 - 1 (1,073,741,823) 个字符

二进制字符串类型 
类型	描述
binary	长度为 n 字节的固定长度二进制数据,范围从 1 到 8,000 的值。存储大小为 n 字节。
varbinary	可变长度二进制数据。n 可以取从 1 到 8,000 的值。最大的存储大小为 2^31-1 字节
image	长度可变的二进制数据,从 0 到 2^31-1 (2,147,483,647) 个字节











 
Exec sp_renamedb ‘student’,’s’//改变数据库的名字
Exec sp_rename ‘student’,’ss’//改变表的名字
--判断是否存在该数据库,存在就删除
if (exists (select * from sys.databases where name = 'testHome'))
    drop database testHome
go
-----------------------------
--判断某个表或对象是否存在
if (exists (select * from sys.objects where name = 'classes'))
    print '存在';
go
if (exists (select * from sys.objects where object_id = object_id('student')))
    print '存在';
go
if (object_id('student', 'U') is not null)
    print '存在';
go
----------------------------------
--判断该列名是否存在,如果存在就删除
if (exists (select * from sys.columns where object_id = object_id('student') and name = 'idCard'))
    alter table student drop column idCard
go
if (exists (select * from information_schema.columns where table_name = 'student' and column_name = 'tel'))
    alter table student drop column tel
go
---------------------------------------
--判断是否存在当前table
if (exists (select * from sys.objects where name = 'classes'))
    drop table classes
go
-----------------------------------------
--备份、复制student表到stu
select * into stu from student;
select * into stu1 from (select * from stu) t;
---------------------------------
--drop database student
create database student
on
(
	name = 'student_data',
	filename = 'd:\data\student.mdf',
	size = 10,
	filegrowth = 10,
	maxsize = 100
)
log on (
	name = 'student_log',
	filename = 'd:\data\student.ldf',
	size = 10,
	filegrowth = 10,
	maxsize = 100
))

use student
--drop table student
create table student
(
	sid  int identity primary key,--主键约束
	sname varchar(8) not null,
	gender char(2) check(gender='男' or gender= '女'),--检查约束
	age tinyint,
	idcard char(18) unique,--唯一约束
	addr varchar(100) default('河北')--默认约束
)

alter table student
drop constraint DF__student__addr__0519C6AF--删除约束

--往表中插入单条数据
insert into student(sname,gender)values('张三','男')
insert into student values('李四','男','19','222222222222222222','河北北方学院')
select * from student

alter table student
add sduty varchar(6)—添加列
alter table student--删除列
drop column idcard,addr
删除列必须先删除约束

--往表中插入多组数据
insert into student
select 'bb','女','16' union
select 'bc','女','17' union
select 'bd','男','18' 
select * from student

注意:如果表的定义允许,则可以在insert操作中省略某些列。省略的列必须满足以下某个条件:
	  该列定义为允许null值(无值或空值);在表定义中给出默认值。这表如果不给出值,将使用默认值。
truncate table student--一次性把表中数据删掉

delete from student where sname = 'bb'--条件性删除符合条件的行

update student set sname = 'cc',gender = '男' where age = 18--条件性修改,如果没有where语句所有的都修改

create table marks
(
	mid int identity primary key,--主键约束
	sid int references student,--外键约束
	english tinyint
)

--级联约束
alter table marks
add constraint fk_sid foreign key(sid) references student on delete cascade

insert into marks values(3,25)
select * from  marks

--添加约束
alter table student
add constraint pk_sid primary key(sid),--添加主键约束
constraint ck_age check(age>18 and age<39),--添加check约束
constraint df_addr default('aa') for addr,--添加默认约束
constraint uq_idcard unique(idcard),--添加唯一约束
constraint fk_sid foreign key(sid) references student--添加外键约束
--查询
1.select sname,age 
from student--查询相应的列
2.select * 
from student--查询所有的列
3.select sname as 'bd','男' = gender 
from student--查询符合条件的列
4.select top 10 * 
from student--查询前10行
5.select top 10 percent * 
from student --查询前10%行
6.select * 
from student 
order by age asc--升序排列
7.select * 
from student 
order by age desc--降序排列
8.select sname,age,sid 
from student 
order by age(desc),sid —-先按age排序再按sid排序,desc是降序排列,如果不明确顺序按默认顺序(升序)
9.select sname,age,sid 
from student 
order by 2,3 –按列位置排序(输出同上)
10.select top 1 * 
from student 
order by age desc--查询出年龄最大的信息
11.select distinct gender 
from student--输出gender列,列中数据不重复
12.select * 
from student 
where age>20--查询符合条件的行
13.select * 
from student 
where gender is null--查询性别是空的行
14.select * 
from student 
where age>=20 and age<=30--
15.select * 
from student 
where age between 20 and 30--同上

--模糊查询
--[abc]:abc中其中任何一个
--[^abc]:不能abc中其中任何一个
--[a-z][0-9]
-- _:表示任何一个字符
--%:表示任意个字符
1.select * 
from student 
where sname like 'b%'--姓名以c开头的所有数据
2.select * 
from student 
where sname like '%[abc]_'--倒数第2个字符是abc中任意一个的数据
--聚合函数
1.select AVG(age) 
from student--age列的平均值
2.select SUM(age) 
from student--age列的总和
3.select MAX(age) 
from student--age列的最大值
4.select MIN(age) 
from student--age列的最小值
5.select COUNT(*) 
from student--所有行的个数
6.select COUNT(age) 
from student--age不为空的行个数
7.select gender,COUNT(*) 
from student 
group by gender--按照gender分组后再求各个组的COUNT(*)
8.select gender,AVG(age) 
from student 
group by gender--按照gender分组后再求各个组的AVG(age)
9.select gender,COUNT(*) 
from student 
group by gender 
having COUNT(*)>2--按照gender分组后再求各个组COUNT(*)大于的组和列数
10. select VAR(age) 
from student--age列的方差

where 和 having 的差别:where在数据分组前进行过滤,having在数据分组后进行过滤
	例如: select id,count(*) from where price>4 group by id having count(*)>2
--输出参加考试人的信息
10.select * 
from student 
where sid in(select sid from marks)--子查询
-------------------
11.Select cust_name,
Cust_state,
select count(*)
          From orders
		  Where orders.cust_id = customers.cust_id) AS orders
From customers
Order by cust_name
-------------------
select * 
from student 
where age>(select MIN(age) from student)--子查询
---------------------------------------
where和order by同时使用时order by必须位于where之后
group by子句必须出现在where子句之后,order by 子句之前
where 语句后or和and同时使用时先执行and后执行or,所以or的内容必须加()
1.select sname,gender,sid 
from student 
where not sname = ‘张三’
2.select sname,gender,sid 
from student 
where sname != ‘张三’
3.select sname,gender,sid 
from student 
where sname <> ‘张三’

多表查询:如果查询的结果需要来自多个表
表联接:
    内联接:两个表关联的两列都有的数据所对应的行合并到总表中去
    外联接:左外联接(左联接),右外联接(右联接)
        左联接: 先把左边的表复制到总表中,然后把右表中和左表所关联的列的数据显示出来,没关联的数据显示为null
        右联接和左联接类似
1.select * 
from student inner join marks 
on student.sid = marks.sid--内链接
2.select * 
from student st inner join marks ms 
on st.sid = ms.sid--同上
3.select * 
from student st left join marks ms 
on st.sid = ms.sid--左链接
4.select * 
from student st right join marks ms 
on st.sid = ms.sid--右链接
-------创建联接
1.Select vend_name,prod_name,prod_price
From Vendors,Products
Where Vendors.vend_id=Products.vend_id
2.Select cust_name,cust_contact
From Customers AS C,Orders AS O,OrderItems AS OI
Where C.cust_id=O.cust_id
  And OI.order_num=O.order_num
  And Prod_id = ‘RGAN01’
注意:表别名只在查询执行中使用,与列表名不一样,,表别名不返回到客户机
-----自联接:通常作为外部语句用来替代从相同表中检索数据的使用子查询语句
假如想发送一封信件给为Jim Jones所在的公司工作的所有客户。首先先找到Jim Jones工作的公司,然后找出为此公司工作的客户
Select cust_id,cust_name,cust_contact
From Customers
Where cust_name=(select cust_name
   From Customers
   Where cust_contact=’Jim Jones’)
自联接代码如下:
Select c1.cust_id,c1.cust_name,c1.cust)contact
From Customers AS c1,Customers AS c2
Where c1.cust_name = c2.cust_name
  And c2.cust_contact = ‘Jim Jones’;
---自然连接:排除相同列的多次出现。你只能选择那些唯一的列,这一般是通过对表使用通配符(select*),对所有其他表的列使用明确的子集来完成的。
事实上,迄今为止我们建立的每个内部联接都是自然连接
Select C.*,O.order_num,O.order_date,OI.prod_id,OI.quantity,OI.item_price
From Custemers as C,Orders as O,OrderItems as OI
Where C.cust_id=O.cust_id
  And OI.order_num=O.order_num
  And prod_id = ‘RGAN01’;
---组合查询:使用union
使用多条where子句查询:
Select cust_name,cust_contact,cust_email
From Costomers
Where cust_state in(‘IL’,’IN’,’MI’)
Or cust_name=’Fun4All’;
使用union查询:
Select cust_name,cust_contact,cust_email
From Costomers
Where cust_state in(‘IL’,’IN’,’MI’)
Union
Select cust_name,cust_contact,cust_email
From Customers
Where cust_name=’Fun4All’;
Union使用规则:union必须由两条或两条以上的select语句组成,语句之间用union分隔;union中的每个查询必须包含相同的列,表达式或聚集函数(不过各个列不需要以相同的次序列出);列数据类型必须兼容:类型不必完全相同,但必须是DBMS可以隐含地转换的类型
在使用union时,重复的行被自动取消,如果想返回所有的匹配行,可使用union all。
--对组合查询结果排序:在使用union时,只能使用一条order by子句,它必须出现在最后一条select语句之后
Select cust_name,cust_contact,cust_email
From Costomers
Where cust_state in(‘IL’,’IN’,’MI’)
Union
Select cust_name,cust_contact,cust_email
From Customers
Where cust_name=’Fun4All’
Order by cust_name,cust_contact;
插入检索出的数据:
Insert into Customers(
	(cust_name,
Cust_addr,
Cust_email)
Select name,
		Addr,
		Email
From  CustNew
从一个表复制到另一个表:
Select *
Into CustCopy
From Customers;
使用select into时,有些需要知道的东西:
	任何select选项和子句都可以使用,包括where和group 不用;可利用联接从多个表中插入数据;不管从多少个表中检索数据,数据都只能插入到单个表中
视图
--视图:一个虚拟的表,其实只存放了一个查询语句(作用是为了表的安全性)
drop view myview--删除视图
create view myview--创建视图
as
select * from student
go

select * from myview
insert into myview values('peng','男',20)
delete from myview where sid=5
update myview set sname='dd',gender='女',age=23 where sid>5
--视图中只能对视图中有的字段操作(insert,delete,update)
-----创建视图
create view StuMarks as
select student.sid,sname ,gender,english
from student,marks
where student.sid=marks.sid
select * from StuMarks
select sid,sname,gender
from StuMarks
where english>60

drop view StuMarks--删除视图
--覆盖或更新视图必须先drop它,然后重新创建

--创建格式化视图
create view VendorLocation as
select RTRIM(vend_name)+'('+RTRIM(vend_country)
+')' as vend_title
from Vendors;
--------------------------
--索引:相当于表的目录。作用:加快查询速度
	--常用:聚集索引,非聚集索引
	--一个表最多有一个聚集索引
	--某列创建一个主键约束的时候,系统会自动在该列上创建一个聚集索引,聚集索引会按照表升序排列
	--非聚集不会引起表的排序,一个表可以有很多非聚集索引
create clustered index myindex on student(age)--在age列上创建聚集索引
--如果列作为order by或where条件时创建索引
--不能创建索引的条件:如果列中重复的数据比较多;大数据类型时。
create nonclustered index myindex on student(age)--在age列上创建非聚集索引
drop index myindex on student--删除索引
--------------------------
--事务处理
--事务:可以把多个数据库操作语句,看做一个整体,若其中任何一条语句出现错误,则可以恢复到最初状态
create table bank
(
cardno char(3) primary key,
cname varchar(20) not null,
balance money
)
alter table bank
add constraint ck_balance check(balance>=0)
insert into bank values('123','aa',5000)
insert into bank values('456','bb',1000)
--
select * from bank

declare @errorsum int=0
begin transaction--开始事务
update bank set balance-=10000 where cardno='123'
set @errorsum=@@ERROR
update bank set balance+=10000 where cardno='456'
set @errorsum+=@@ERROR
if(@errorsum=0)
begin
	commit transaction--提交事务
end
else
begin 
	rollback transaction--回滚事务
end
----------
--	 事务处理用来管理insert,update,和delete语句。不能回退select,create和drop语句
begin transaction

commit transaction
--二者之间的语句必须完全执行或完全不执行
--rollback用来回退SQL语句
--save transaction startorder 设置保留点startorder
select * from student
begin transaction
insert into student values('jia','男',20)
save transaction startorder
insert into student values('xiao','男女',21)
if @@ERROR <> 0 rollback transaction startorder
insert into student values('peng','男',22)
if @@ERROR <> 0 rollback transaction startorder
commit transaction
--事务的个性质:
	--A(原子性):把多个数据库操作语句,看做一个整体,若其中任何一条语句出现错误,则可以恢复到最初状态
	--C(一致性):事务的前后数据总和保持不变
	--I(隔离性):一个事务执行完了以后其他事务才能执行
	--D(永久性):如果事务没有发生任何错误,那么数据将永久保存
--存储过程:类似于c#中的方法
drop procedure sp_student_select—删除存储过程
--创建存储过程
create procedure sp_student_select--创建查询存储过程
as
select * from student 
go--批处理标志,修改和创建都用go
exec sp_student_select--调用存储过程

alter procedure sp_student_select--修改存储过程
@age tinyint
as
select * from student where age>@age
go
exec sp_student_select 20--把给@age

create procedure sp_student_insert--创建插入数据存储过程
@sname varchar(10),
@gender char(2),
@age tinyint
as
insert into student values(@sname,@gender,@age)
go
exec sp_student_insert 'peng','男',26
create procedure sp_student_delete--创建删除存储过程
@sid int
as
delete from student where sid=@sid
go
exec sp_student_delete 9

create procedure sp_student_update--创建修改存储过程
@sname varchar(10),
@gender char(2),
@age tinyint,
@sid int
as
update student set sname=@sname,gender=@gender,age=@age where sid=@sid
go
exec sp_student_update 'xiao','男',29,6
存储过程的insert、select、delete、update四个例子:
1.	insert
Console.WriteLine("请输入姓名");
string sname = Console.ReadLine();
Console.WriteLine("请输入性别");
string gender = Console.ReadLine();
Console.WriteLine("请输入年龄");
byte age = byte.Parse(Console.ReadLine());
string CONNSTR="data source=.;initial catalog=student;integrated security=true";
SqlConnection sqlConn = new SqlConnection(CONNSTR);
SqlCommand sqlCmd = sqlConn.CreateCommand();
string CONNSTR = "data source=.;initial catalog=student;integrated security=true";
SqlConnection sqlConn = new SqlConnection(CONNSTR);
SqlCommand sqlCmd = sqlConn.CreateCommand();
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "sp_student_insert";
SqlParameter[] sps =
{
       new SqlParameter("@sname",sname),
       new SqlParameter("@gender",gender),
       new SqlParameter("@age",afe)
};
sqlCmd.Parameters.AddRange(sps);
//sqlCmd.CommandText = "insert into student values('"+sname+"','"+gender+"',"+age+")";
try
{
        sqlConn.Open();
        int row = sqlCmd.ExecuteNonQuery();
        if (row > 0)
        {
              Console.WriteLine("添加成功");
        }
}
catch (SqlException se)
{
       Console.WriteLine(se.Message);
}
finally
{
    sqlConn.Close();
}
2.select
string CONNSTR = "data source=.;initial catalog=student;integrated security=true";
SqlConnection sqlConn = new SqlConnection(CONNSTR);
SqlCommand sqlcmd = sqlConn.CreateCommand();
sqlcmd.CommandText = "sp_student_select";
try
 {
    sqlConn.Open();
    SqlDataReader reader = sqlcmd.ExecuteReader();
    if (reader != null)
    {
        Console.Write("学号\t");
        Console.Write("姓名\t");
        Console.Write("性别\t");
        Console.WriteLine("年龄\t");
        while (reader.Read())
        {
            Console.Write(reader.GetInt32(0) + "\t");
            Console.Write(reader.IsDBNull(1) ? "\t" : reader.GetString(1) + "\t");
            Console.Write(reader.IsDBNull(2) ? "\t" : reader.GetString(2) + "\t");
            Console.WriteLine(reader.IsDBNull(3) ? "\t" : reader.GetByte(3) + "\t");
         }
     }
   }
catch (SqlException se)
{
     Console.WriteLine(se.Message);
}
finally
{
       sqlConn.Close();
}
3.delete
string CONNSTR = "data source=.;initial catalog=student;integrated security=true";
SqlConnection sqlConn = new SqlConnection(CONNSTR);
SqlCommand sqlCmd = sqlConn.CreateCommand();
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "sp_student_delete";
SqlParameter sp = new SqlParameter("@sid",5);
sqlCmd.Parameters.Add(sp);
try
{
     sqlConn.Open();
     int row = sqlCmd.ExecuteNonQuery();
     if (row > 0)
     {
         Console.WriteLine("删除成功");
      }
}
catch(SqlException se)
{
      Console.WriteLine(se.Message);
}
finally
{
     sqlConn.Close();
}
4.update
string CONNSTR = "data source=.;initial catalog=student;integrated security=true";
SqlConnection sqlConn = new SqlConnection(CONNSTR);
SqlCommand sqlCmd = sqlConn.CreateCommand();
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "sp_student_update";
SqlParameter[] sps =
{
       new SqlParameter("@sname","jj"),
       new SqlParameter("@gender","男"),
       new SqlParameter("@age",33),
       new SqlParameter("@sid",3)
};
sqlCmd.Parameters.AddRange(sps);
try
{
        sqlConn.Open();
        int row = sqlCmd.ExecuteNonQuery();
        if (row > 0)
        {
              Console.WriteLine("修改成功");
        }
}
catch (SqlException se)
{
       Console.WriteLine(se.Message);
}
finally
{
    sqlConn.Close();
}
-------------------------------------------------------
--触发器:可以与特定表上的indert、update和delete操作(或组合)相关联
create trigger customer_state
on Customers
for insert, update
as
update Customers
set cust_state = UPPER(cust_state)
where Customers.cust_id = inserted.cust_id
--------------------------
--时间函数
print getdate() --获取当前的时间
print year(getdate())--获取年
print month(getdate())--获取月
print day(getdate())--获取日
print datepart(yyyy,'2015-06-02')--获取年
print datepart(mm,'2015-06-02')+2--获取月,结果是8
print datepart(dd,'2015-06-02')--获取日
print datename(dd,'2015-06-02')+'aaa'--返回字符串型,结果是2aaa
print datediff(yy,'2010-01-22','2011-04-23')--显示年或月,日的差结果:1
print dateadd(yy,5,'2012-05-22')--加日期结果:2017-05-27
--数学函数
Print abs(-1) --绝对值.结果:1
Print ceiling(10.001) --小数点后面的数大于0,就进1;001大于0,所以结果:11
Print floor(10.99) --取小数点前面的数结果:10
print round(10.5,0)--小数点后第一个数加一位大于5进一位,否则参数及后面的数变0,所以结果:11.0
print round(10.598,1)--小数点后第二个数加一位大于5进一位,结果:10.600
print round(10.538,1)--结果:10.500
print round(10.594,2)--结果:10.590

--字符串函数
print charindex('ab','abc')--判断一个字符串是否包含另一个字符串,包含返回位置下标,不包含则返回0.结果:1
print len('abcd')--字符串长度.结果:4
print substring('abcd',1,3)--从第1个位置开始,截取3个字符,结果:abc
print left('abcd',2)--从左边截取2个.结果:ab
print right('abcd',2)--从右边截取2个.结果:cd
print space(3)--访问由3个空格组成的字符串
print ltrim('  abc')--去掉字符串左边的空格
print rtrim('aaa  ')--去掉字符串右边的空格
print ltrim(rtrim('   abc   '))--去掉字符串两边的空格
print replace('abcd','a','11')--把字符串中的2替换成第11。结果:11bcd
print stuff('abcdef',2,3,'11')--从字符串第2个位置开始把之后的3个字符替换成11.结果:a11ef

--系统函数
print convert(varchar(20),123)+'aaa'--把123转换成字符串。结果:123aaa
print cast(123 as varchar(10))+'aaa'--把123转换成字符串。结果:123aaa
print convert(varchar(2),123)+'aaa'--结果:*aaa.如果varchar长度不够返回*

--变量:系统变量,自定义变量
--系统变量:@@rowcount:上一条sql语句受影响的行数
print @@rowcount
         --@@error:上一条sql的错误号码,若有错误则是一个大于的数,否则是0
print @@error         
         --@@identity:获取表中最大的标识值  

--自定义变量:
declare @name varchar(10) = '123'
print @name

declare @name varchar(10)
set @name = '123' --set一次只能给一个变量赋值
print @name

declare @name varchar(10)
declare @age tinyint
select @name='123',@age=10--select可以给多个变量赋值
print @name
print @age

declare @age tinyint
select @age=MAX(age) from student--select可以给从表中赋值
print @age
-------------------------------------------------
--配置函数
set datefirst 7;--设置每周的第一天,表示周日
select @@datefirst as '星期的第一天', datepart(dw, getDate()) AS '今天是星期';
select @@dbts;--返回当前数据库唯一时间戳
set language 'Italian';
select @@langId as 'Language ID';--返回语言id
select @@language as 'Language Name';--返回当前语言名称
select @@lock_timeout;--返回当前会话的当前锁定超时设置(毫秒)
select @@max_connections;--返回SQL Server 实例允许同时进行的最大用户连接数
select @@MAX_PRECISION AS 'Max Precision';--返回decimal 和numeric 数据类型所用的精度级别
select @@SERVERNAME;--SQL Server 的本地服务器的名称
select @@SERVICENAME;--服务名
select @@SPID;--当前会话进程id
select @@textSize;
select @@version;--当前数据库版本信息
------------------------------------------------
--系统统计函数
select @@CONNECTIONS;--连接数
select @@PACK_RECEIVED;
select @@CPU_BUSY;
select @@PACK_SENT;
select @@TIMETICKS;
select @@IDLE;
select @@TOTAL_ERRORS;
select @@IO_BUSY;
select @@TOTAL_READ;--读取磁盘次数
select @@PACKET_ERRORS;--发生的网络数据包错误数
select @@TOTAL_WRITE;--sqlserver执行的磁盘写入次数

-------------------------------------------------
if-else判断语句
if <表达式>
    <命令行或程序块>
else if <表达式>
    <命令行或程序块>
else
    <命令行或程序块>
          示例 
if简单示例
if 2 > 3
    print '2 > 3';
else
    print '2 < 3';
--if while
--if while
--if
--begin{
--end}
--计算1到100的和
declare @sum int=0
declare @idx int=1
while(@idx<101)
begin
	set @sum+=@idx
	set @idx+=1
end
print @sum
---------------
declare @sum int=0
declare @idx int=1
while(@idx<101)
begin
	if(@sum>=400)
	begin
	  break
	end
	set @sum+=@idx
	set @idx+=1
end
print @sum
---------------
declare @row int=0
declare @col int=0
declare @star varchar(100)=''
while(@row<5)
begin
set @star=''
set @col=0
	while(@col<5)
	begin
		set @star+='*'
		set @col+=1
	end
	print @star
	set @row+=1
end
-------------------------

--计算字段
--拼接字段
Select vend_name + ‘(’ + vend_country + ‘)’ 
from Vendors 
order by ven_name;
结果:Bear Emporium        (USA     )
      Bears R Us            (USA     )
      Furball Inc           (England     )
注意:Access,SQL Server和Sybase中使用+号。DB2,Oracle,PostgreSQL和Sybase中只用||.MYSQL中的拼接使用concat()函数
Select vend_name || ‘(’ || vend_country || ‘)’ 
from Vendors 
order by ven_name;
Select vend_name concat( ‘(’ , vend_country , ‘)’ )
from Vendors 
order by ven_name;
--去掉空格
RTRIM()去掉右边的所有空格;LTRIM()去掉左边的所有空格;TRIM去掉左右两边的空格
Select RTRIM(vend_name) + ‘(’ + RTRIM(vend_country) + ‘)’ from Vendors order by ven_name;
结果:
      Bear Emporium(USA)
      Bears R Us(USA)
      Furball Inc(England)
--------列别名:一个字段或值的替换名,用AS赋予 ,列别名可以被引用
Select RTRIM(vend_name) + ‘(’ + RTRIM(vend_country) + ‘)’ AS vend_title from Vendors 
order by ven_name;
结果:      vend_title
      Bear Emporium(USA)
      Bears R Us(USA)
      Furball Inc(England)
-------执行算数计算(+,-,*,/)
输入:Select id,quantity,price from OrderItems where num = 20008;
输出:id	quantity	price
      1	         5          2.0000
      2          6           3.0000
      3         10          1.0000
输入:Select id,quantity,price,
quantity*price AS expanded_price 
from OrderItems 
where num = 20008;
输出:id	quantity	    price	   expanded_price
      1	         5          2.0000         10.0000
      2          6           3.0000         18.0000
      3         10          1.0000          10.0000
客户机可以使用这个新计算列,就像使用其他列一样
使用数据处理函数
1.	文本处理函数
Upper()函数:将文本转换成大写
输入:Select vend_name,Upper(vend_name) AS 
vend_nane_upcase 
from Vendors 
order by vend_name
   输出:vend_name			vend_name_upcase
		     aaa                  AAA
             bbb                  BBB
常用的文本处理函数:
	Left()  (或使用子字符串函数) 返回串左边的字符
Length()  (也使用datalength()或len())返回串的长度
Lower()  (Access使用Lcase())  将串转换为小写
Ltrim()               去掉串左边的空格
Rtrim()                去掉串右边的空格
Right()  (或使用子字符串函数) 返回串右边的字符
Soundex()                 返回串的soundex值
Upper()  (Access使用Ucase())    将串转换为大写
2.  数值处理函数
    ABS()			返回一个数的绝对值
    COS()			返回一个角度的余弦
    EXP()			返回一个数的指数值
PI()     		返回圆周率
SIN()			返回一个角度的正弦值
SQRT()			返回一个数的平方根
TAN()			返回一个角度的正切
--case 只能用于赋值
--简单case 语句,搜索case
declare @g bit=1--1男,女
--if(@g=1)
--begin
--	print '男'
--end
--else
--begin 
--	print '女'
--end//结果:男
declare @s char(2)
set @s=case @g when 1 then '男' else '女' end--简单case语句(常数的判断)
print @s//结果:男

declare @m tinyint=82
declare @r char
set @r=case--搜索case语句(范围的判断)
when @m>=90 then 'a'
when @m>=80 then 'b'
when @m>=70 then 'c'
when @m>=60 then 'd'
else 'e'
end
print @r//结果:b

1.一道SQL语句面试题,关于group by
表内容:bs
bsrq       res
2005-05-09 胜
2005-05-09 胜
2005-05-09 负
2005-05-09 负
2005-05-10 胜
2005-05-10 负
2005-05-10 负
如果要生成下列结果, 该如何写sql语句?
  bsrq     胜 负
2005-05-09 2  2
2005-05-10 1  2
答案:
create table bs
(
bsrg datetime,
res char(2)
)
insert into bs values('2005-05-09','胜')
insert into bs values('2005-05-09','胜')
insert into bs values('2005-05-09','负')
insert into bs values('2005-05-09','负')
insert into bs values('2005-05-10','胜')
insert into bs values('2005-05-10','负')
insert into bs values('2005-05-10','负')
--truncate table bs
select * from bs
select bsrg,'胜'=SUM(case res when '胜' then 1 else 0 end),'负'=SUM(case res when '负' then 1 else 0 end)
from bs group by bsrg
不错的sql语句
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用)法一:select * into b from a where 1<>1法二:select top 0 * into b from a
2、说明:拷贝表(拷贝数据,源表名: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 '"&Server.MapPath(".")&"data.mdb" &"' where..

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 viewname 

7、说明:在线视图查询(表名1:a )
select * from (SELECT a,b,c FROM a) T where t.a > 1;
10、说明:两张关联表,删除主表中已经在副表中没有的信息 
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )
24、说明:选择从10到15的记录
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc
--------------------------------------------------------------------------------------------------
集合运算 :操作两组查询结果,进行交集、并集、减集运算 
1、 union和union all进行并集运算 
--union 并集、不重复
select id, name from student where name like 'ja%'
union
select id, name from student where id = 4;
 --并集、重复
select * from student where name like 'ja%'
union all
select * from student;
2、 intersect进行交集运算 
--交集(相同部分)
select * from student where name like 'ja%'
intersect
select * from student;
3、 except进行减集运算 
--减集(除相同部分)
select * from student where name like 'ja%'
except
select * from student where name like 'jas%';

----------------------------------------------------------------------------------------
集合:
命名空间:system.collections
arraylist:容量动态改变可以是一维数组
hashtalble:哈希表二维数组,第一列主键key,第二列值(数据)value
queue:队列(先进先出的数据结构)
stack:栈(先进后出的数据结构)
arraylist
容量可以动态改变的数组
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace 集合
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList(1);//初始大小为1
            list.Add(15);
            list.Add(20);
            list.Add(30);
            list.AddRange(new int[3]{1,2,3});//一次可以装多个数据
            Console.WriteLine(list.Capacity);//获取当前容量
            list.Clear();//清空数组中数据
	    bool b = list.Contains(1);//是否包含
            Console.WriteLine(list.Count);//包含实际元素的个数
            int i = list.IndexOf(20);//从前往后查询,如果包含返回位置下标,不包含返回-1
            i = list.LastIndexOf(20);//从后往前查询,如果包含返回位置下标,不包含返回-1;
            list.Remove(20);//从前往后查询删除,删除一个后结束
            list.RemoveAt(2);//按位置删除
            list.Reverse();//反转数组
            list.Sort();//按从小到大排序
            foreach(int s in list)
            {
                Console.WriteLine(s);//15 20 31 1 2 3
            }
            Console.WriteLine(b);//true
        }
    }
}
ArrayList常用的方法:
ArrayList.Add()  往数组中添加数据,一次只能添加一个
ArrayList.AddRange()  可以往数组中添加多个数据
ArrayList. Capacity   获取当前容量
ArrayList..Count   包含实际元素的个数
ArrayList.Clear()   清除数组中的数据
ArrayList.Contains()  判断是否包含某个数据,返回类型是bool
ArrayList.IndexOf()  从前往后查询,如果包含某个数据返回该数据的位置下标,不包含返回-1
ArrayList.LastIndexOf() 从后往前查询,如果包含某个数据返回该数据的位置下标,不包含返回-1
ArrayList.Remove()  删除某个数据
ArrayList.RemoveAt()  按位置删除数据
ArrayList.Reverse()  反转数组
ArrayList.Sort()  升序排序
哈希表 hashtable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
namespace 集合1
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable table = new Hashtable();
            table.Add(1,10);//往哈希表中添加数据
            table.Add(2, 20);
            table.Add(3, 30);
            //int v = (int)table[1];//把哈希表中key=1的value值赋值给v,value属于object类所以要转换
            table[1] = (int)table[1] + 1;//把key为1的value值加1
            //Console.WriteLine(v);
            //table.Clear();//清空哈希表
            //bool b=table.Contains(1);//从key里面找
            bool b = table.ContainsKey(2);//从keys里面找是否包含key=2的数据,包含返回true不包含返回false
            bool b1 = table.ContainsValue(10);//从values里面找
            int c = table.Count;//求元素个数
            Console.WriteLine(b);
            Console.WriteLine(b1);
            Console.WriteLine(c);
            ICollection ic = table.Keys;//返回所有的key,返回类型是接口类型
            foreach (object s in ic)
            {
                Console.WriteLine(s);
            }
            ICollection iv = table.Values;//返回所有的Value,返回类型是接口类型
            foreach (object s in iv)
            {
                Console.WriteLine(s);
            }
            table.Remove(1);//删除 从keys里面查找,有就删除没有不出问题

            foreach (DictionaryEntry s in table)//哈希表中的对象类型是DictionaryEntry
            {
                Console.WriteLine("{0},{1}", s.Key, s.Value);
            }
        }
    }
}
Stack 栈
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Data.SqlClient
namespace 集合2
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack stack = new Stack();
            stack.Push(10);//添加数据
            stack.Push(20);
            //object ob = stack.Pop();//取出栈顶元素,并将栈顶元素删除.ob=20
            object ob = stack.Peek();//取出栈顶元素但不删除.0b=20
            Console.WriteLine(ob);
            Console.WriteLine();
            foreach (object s in stack)
            {
                Console.WriteLine(s);
            }
        }
    }
}
Queue
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
namespace 集合3
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue q = new Queue();
            q.Enqueue(10);//添加数据
            q.Enqueue(20);
            object o = q.Dequeue();//取出对头元素并删除
            o = q.Peek();//取出对头元素不删除
foreach (object s in q)
            {
                Console.WriteLine(s);
            }
        }
    }
}
2例题:请编写一个函数,它可以找出某一字符串中出现次数最多的英文字母(不区分大小写,只考虑A-Z),并且可以返回这个字母以及它出现的个数。比如对于输入字符串“I am a student”,该函数应当返回字母“A”以及个数2。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入一个字符串");
            string str = Console.ReadLine();
            str.ToLower();
            Hashtable table = new Hashtable();
            foreach(char c in str)
            {
                if (table.ContainsKey(c))
                {
                    table[c] = (int)table[c] + 1;
                }
                else
                {
                    table.Add(c,1);
                }
            }
            char ch=' ';
            int max=0;
            foreach(DictionaryEntry s in table)
            {
                if((int)s.Value>max)
                {
                    max=(int)s.Value;
                    ch = (char)s.Key;
                }
            }
            Console.WriteLine("在{0}中,字符{1},出现的此处最多,具体是{2}次",str,ch,max);
        }
    }
}
---------------------------------------------------------------------------
泛型集合
	不会引起装箱操作,效率比较高
using System.Collections.Generic;//这是泛型命名空间
List<>   --->ArrayList  <>中放数据类型
Dictionary<TKEY,TVALUE>   --->Hashtable
Queue<T>   --->Queue
Stack<>   --->Stack
List:例子:往list里放1到100的数且不能重复
	        List<int> list = new List<int>();
            Random ran = new Random();
            int i=1;
            while(i<=100)
            {
                int j=ran.Next(1, 101);
                if (!list.Contains(j))
                {
                    list.Add(j);
                    i++;
                }
            }
            foreach (int s in list)
            {
                Console.Write(s+" ");
            }
Dictionary:
	static void Main(string[] args)
        {
            Dictionary<string, int> dic = new Dictionary<string, int>();
            dic.Add("aa", 12);
            dic.Add("bb", 20);
			int i = dic[“aa”];
dic[“aa”] +=1;
            Dictionary<string, int>.KeyCollection kc = dic.Keys;
            foreach (string s in kc)
            {
                Console.WriteLine(s);
            }
            Dictionary<string, int>.ValueCollection vc = dic.Values;
            foreach (int s in vc)
            {
                Console.WriteLine(s);
            }
            foreach (KeyValuePair<string, int> s in dic)
            {
                Console.WriteLine("{0},{1}", s.Key, s.Value);
            }
        }
Queue<T>, Stack<>省略参照Queue和Stack
--------------------------------------------------------------------
表与表之间的关系:
	一对一:外键放在哪个表中都可以。
	一对多:外键放在“多”的表中。
	多对一:外键放在“多”的表中。
	多对多:添加第三个表,在第三个表中至少存放前两个表的外键
数据库的设计好坏的评价标准:
	范式一:表列的原子性(每一列的数据不能再拆分)
	范式二:每个表只描述一件事情(在范式一的基础上)
	范式三:表不能存放其他表的非主键列,若要存放的话,只能存放其他表的主键列


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值