SQL实战大全:数据库创建、表设计、约束、权限、事务、索引、视图、存储过程,从入门到高级,完整学习指南
-- 启用xp_cmdshell以执行DOS命令exec sp_configure 'show advanced options',1RECONFIGUREexec sp_configure 'xp_cmdshell',1RECONFIGURE-- 创建项目文件夹exec xp_cmdshell 'md d:\project'gouse master go-- 创建bbsDB数据库if exists(select name from sysdatabases where name='bbsDB') drop database bbsDBgocreate database bbsDBon( name='bbsDB', filename='d:\project\bbsBD.mdf', size=10mb, filegrowth=15%)log on( name='bbsDB_log', filename='d:\project\bbsBD_log.ldf', size=3mb, maxsize=20mb, filegrowth=15%)
use bbsDBgoif exists(select name from sysobjects where name='bbsUsers') drop table bbsUsersgocreate table bbsUsers( UID int identity(1,1) not null, --用户编号 Uname varchar(15) not null, --用户名 Upassword varchar(10) not null, --密码 Uemail varchar(20), --邮箱 Usex bit not null, --性别 Uclass int , --用户等级 Uremark varchar(20), --备注信息 UregDate datetime not null, --注册日期 Ustate int, --状态 Upoint int --用户积分)
-- 主键约束if exists(select name from sysobjects where name='PK_UID') alter table bbsUsers drop constraint PK_UIDgoalter table bbsUsersadd constraint PK_UID primary key (UID)go-- 默认密码值 888888if exists(select name from sysobjects where name='DF_Upassword') alter table bbsUsers drop constraint DF_Upasswordgoalter table bbsUsersadd constraint DF_Upassword default ('888888') for Upassword go-- 密码约束:必须大于6个字符if exists(select name from sysobjects where name='CK_Upassword') alter table bbsUsers drop constraint CK_Upasswordgoalter table bbsUsersadd constraint CK_Upassword check(Len(Upassword)>=6)GO-- 默认注册日期为当前时间if exists(select name from sysobjects where name='DF_UregDate') alter table bbsUsers drop constraint DF_UregDategoalter table bbsUsersadd constraint DF_UregDate default (getdate()) for UregDatego-- 邮箱格式约束if exists(select name from sysobjects where name='CK_Uemail') alter table bbsUsers drop constraint CK_Uemailgoalter table bbsUsersadd constraint CK_Uemail check (Uemail like '%@%')go-- 外键约束示例if exists (select name from sysobjects where name='FK_TsID') alter table bbsTopic drop constraint FK_TsIDgoalter table bbsTopicadd constraint FK_TsID foreign key (TsID) references bbsSection(SID)go-- 唯一约束if exists (select name from sysobjects where name='UQ_stuID') alter table bbsTopic drop constraint UQ_stuIDgoalter table bbsTopicadd constraint UQ_stuID unique (stuID)
-- 第一曲:添加SQL登录用户use masterexec sp_addlogin 'zhouxuan', '密码'go-- 第二曲:分配指定数据库访问权限use 需要分配的数据库goexec sp_grantdbaccess '分配的用户', '你的登录账号(必须有权限)'go-- 第三曲:分配具体权限grant 权限 [on 表名] to 数据库用户-- 权限:insert, delete, update, select, create table
-- 声明declare @name varchar(8)declare @seat int -- 赋值set @name = '张三'select @seat = stuseat from stuinfo where stuname='李四'-- 注意事项-- 1. select可以同时对多变量赋值-- 2. set必须保证查询语句返回单行单列-- 3. 当查询无结果时,set赋值为NULL,select保持原值
@@error -- 最后一个T-SQL语句的错误号@@identity -- 最后一次插入的标识值@@rowcount -- 受上一个SQL语句影响的行数@@servername -- 本地服务器名称@@version -- SQL Server的版本信息
-- 日期部分缩写-- 年份:yy, yyyy-- 季度:qq, q-- 月份:mm, m-- 日期:dd, d-- 星期:wk, ww-- 小时:hh-- 分钟:mi, n-- 常用函数dateadd(dd, 3, 需要添加的时间) -- 添加天数datediff(dd, 当前时间, 其他时间) -- 计算日期差datepart(ss, getdate()) -- 返回指定部分
-- IF-ELSEif(@sumError > 0)begin print '交易失败'endelse begin print '交易成功'end-- WHILE循环while(1=1)begin if(@n > 0) update ... else breakend-- CASE表达式select 是否通过 = case when writtenExam >= 60 and LabExam >= 60 then '通过' else '未通过'endfrom stuInfo
use bankDBgobegin tran -- 开始事务 declare @sumError int set @sumError = 0 -- 更新账户余额 update bank set currentMoney = currentMoney + 500 where customerName = '张三' set @sumError = @sumError + @@error -- 插入交易记录 declare @ka char(10) select @ka = cardID from bank where customerName = '张三' insert into transInfo(cardID, transType, transMoney, transDate) values(@ka, '存入', 500, Getdate()) set @sumError = @sumError + @@error if(@sumError > 0) begin rollback tran -- 回滚事务 print '存钱失败,请确认输入无异常' end else begin commit tran -- 提交事务 print '存钱成功,请查询余额' endgo
use stuDBgo-- 删除现有索引if exists(select name from sysindexes where name='IX_stuMarke_writtenExam') drop index stuMarks.IX_stuMarke_writtenExamgo-- 创建非聚集索引,填充因子30%create nonclustered index IX_stuMarke_writtenExam on stuMarks(writtenExam)with fillfactor = 30 -- 填充因子%go-- 使用索引查询select * from stuMarks with (index(IX_stuMarke_writtenExam)) where writtenExam between 60 and 90
use studbgoif exists(select * from sysobjects where name='view_name') drop view view_namegocreate view view_nameas <select 语句>go-- 使用视图select * from view_name
-- 数据库信息exec sp_databases -- 列出所有数据库exec sp_renamedb 'db1', 'db2' -- 重命名数据库exec sp_helpdb -- 数据库信息-- 表信息exec sp_tables -- 列出所有表exec sp_columns stuInfo -- 查看表列信息exec sp_help stuInfo -- 查看表所有信息exec sp_helpconstraint stuInfo -- 查看表约束exec sp_helpindex stuMarks -- 查看表索引-- 其他exec sp_helptext 'view_name' -- 查看视图定义exec sp_stored_procedures -- 列出所有存储过程exec sp_password -- 修改登录密码
use stuDBgoif exists(select * from sysobjects where name='proc_stu') drop procedure proc_stugocreate procedure proc_stu @writtenpass int, -- 输入参数:笔试及格线 @labPass int, -- 输入参数:机试及格线 @name varchar(50) output -- 输出参数as print '-----------------------' -- 存储过程逻辑go-- 调用存储过程declare @test varchar(50)exec proc_stu 60, 55, @test output-- 或使用参数名调用exec proc_stu @labPass=55, @writtenpass=60, @name=@test output
raiserror('错误信息', 16, 1) -- 16为严重级别,1为状态-- 错误级别大于10时,@@error会被设置
本文全面介绍了MSSQL从基础到高级的各类操作,包括:
✅ 数据库的创建和管理
✅ 数据表的约束设计
✅ 用户权限体系
✅ 变量与流程控制
✅ 事务处理机制
✅ 索引优化技巧
✅ 视图与存储过程
这些知识是每个SQL开发人员必须掌握的技能,建议结合实际项目多加练习。
阅读原文:原文链接