SQL Server使用笔记
1、连接字符串
SQL Server 身份验证,如:"server=yqzhu-peter;database=WindWMNew1_DB;uid=sa;pwd=ABcd1234;Connect Timeout=1000"
2、sa(system administrator),dbo(database owner)
3、SQL 不区分大小写,包括sql语句,数据库名,表名,字段名,变量名,函数名,以及字段中实际值的比较
use wfc_db go create table TestCase( Id int, CaseName varchar(20), UpdateDate datetime ) alter table testcase add [from] varchar(20) insert into Dbo.TestCase values(1, '5555', Getdate(), 'shanghai') insert into Dbo.TestCase values(2, '66666', Getdate(), 'NANJING') select * from Dbo.TestCase declare @aa varchar(20) select @aa = 'SHANGHAI' print @AA if @AA = (select [from] from testcase) print 'yes' else print 'no' select [from] from testcase DELETE FROM TESTCASE WHERE ID = 2
1、当对象名为sql中的关键字时,需要用[]包括
2、创建表时,字段默认是可空的
4、in的两种基本使用方式:
1、简单的方式:select * from testcase where [from] in ('shanghai')
2、组合方式: select * from testcase where [from] in (select [from] from testcase where datediff(day, updatedate, getdate()) = 4)
注意该方式的select子句返回必须为一维表,否则会报错
5、 批量插入: insert into persons(name, classId) select name, 1 from students
或 insert into persons(name, classId) values ('cheng', 1), ('cheng2', 2), ('cheng3', 3),
6、可以定义表变量:
DECLARE @temptb TABLE (
[id] int identity(1,1),
UserID varchar(50)
)
该变量常用于字符串的处理
7、自定义函数:
有三种类型: 1、标量函数 2、内联表值函数 3、多语句表值函数
详细可参考: 1、SQL Function 自定义函数
2、SQLServer:FUNCTION/CURSOR/PROCEDURE/TRIGGER
8、查询重复记录
distinct关键字只能去除重复字段,而不能用于多个字段,如select distinct name from tb_student可行,但select distinct name, age from tb_student会报错
查询重复记录方式是使用group by及having子句,如
select wid, count(*) from TB_CustLotteryInfo where [datetime] > '20160112' group by wid having count(*) > 3