--创建WINDOWS身份验证的帐户 exec sp_grantlogin 'windows 域名域帐户' --创建SQL身份验证的帐户 exec sp_addlogin '帐户名''密码' --创建数据库用户 exec sp_grantdbaccess '登录帐户''数据库帐户' --向数据库用户授权 grant 权限 [表名]to 数据库帐户 use studb go --为zhangshan分配对表stuinfo的select,insert,update的权限 grantselect,insert,update,on stuInfo to zhangshan --为zhangshan分配建表的权限 grantcreatetableto zhangshan
变量和IF ELSE的应用
declare@myavgfloat--声明一个float类型的变量 select@myavg=avg(writtenExam) from stuMarks --把查询结果赋给这个变量 print'本班平均分:'+convert(varchar(5),@myavg) --将变量的值转换为varchar类型并打印出变量的值 if (@myavg>70) begin print'本班笔试成绩优秀,前三名的成绩为' selecttop3*from stuMarks orderby writtenExam desc end else begin print'本班笔试成绩较差,后三名的成绩为' selecttop3*from stuMarks orderby writtenExam asc end
CASE的应用
SELECT 姓名=stuName,学号=stuNo, 笔试成绩=CASE when WrittenExam isnull'缺考' .... elseconvert(varchar(5),WrittenExam) end from stuMark
子查询
--包括子查询的结果集 select stuName from stuInfo where stuno in (select stuNo from stumarks) --不包括子查询的结果集 select stuName from stuInfo where stuno notin(select stuNo from stumarks) --将找到的结果赋给sutno select stuName from stuInfo where stuno=(select stuno from wtumarks where id=4) --将最后个结果赋给stuno select stuName from stuInfo where stuno=(select stuno from wtumarks)
事务的例子
开始事务:begintransaction 提交事务:committransaction 回滚事务:rollbacktransaction 用隐式事务前需要设置:set implicit_transactions on 将隐式事务模式打开 begintransaction --定义变量,用于累计事务执行过程中的错误次数 declare@errorsunint update bank set currentMoney=currentMoner-1000where customername='张三' --累计是否有错误 set@errorsun=@errorsun+@@error update bank set currentMoney=currentMoner+1000where customername='李四' set@errorsun=@errorsun+@@error if@errorsun<>0 begin print'交易失败,回滚事务' rollbacktransaction end else begin print'交易成功,提交事务' committransaction end go