1. 数据库和表操作
创建数据库
sql">CREATE DATABASE DatabaseName;
删除数据库
sql">DROP DATABASE DatabaseName;
创建表
sql">CREATE TABLE TableName ( Column1 DataType1, Column2 DataType2, ... );
删除表
sql">DROP TABLE TableName;
2. 数据操作
插入数据
sql">INSERT INTO TableName (Column1, Column2) VALUES (Value1, Value2);
更新数据
sql">UPDATE TableName SET Column1 = Value1, Column2 = Value2 WHERE Condition;
删除数据
sql">DELETE FROM TableName WHERE Condition;
查询数据
sql">SELECT Column1, Column2 FROM TableName WHERE Condition;
3. 聚合函数
-
计数
sql">SELECT COUNT(*) FROM TableName;
-
求和
sql">SELECT SUM(ColumnName) FROM TableName;
-
平均值
sql">SELECT AVG(ColumnName) FROM TableName;
-
最大值
sql">SELECT MAX(ColumnName) FROM TableName;
-
最小值
sql">SELECT MIN(ColumnName) FROM TableName;
4. 字符串函数
-
连接字符串
sql">SELECT CONCAT(Column1, ' ', Column2) AS FullName FROM TableName;
-
获取子字符串
sql">SELECT SUBSTRING(ColumnName, StartPosition, Length) FROM TableName;
-
字符串长度
sql">SELECT LEN(ColumnName) FROM TableName;
-
转换大小写
sql">SELECT UPPER(ColumnName) FROM TableName; -- 转为大写 SELECT LOWER(ColumnName) FROM TableName; -- 转为小写
5. 日期和时间函数
-
获取当前日期和时间
sql">SELECT GETDATE();
-
提取年份、月份、日期
sql">SELECT YEAR(GETDATE()), MONTH(GETDATE()), DAY(GETDATE());
-
日期加减
sql">SELECT DATEADD(DAY, 7, GETDATE()); -- 当前日期加7天
-
计算两个日期的差异
sql">SELECT DATEDIFF(DAY, '2023-01-01', '2023-12-31'); -- 返回两日期之间的天数
6. 条件语句
-
CASE 语句
sql">SELECT ColumnName, CASE WHEN Condition THEN 'Result1' WHEN Condition THEN 'Result2' ELSE 'OtherResult' END AS AliasName FROM TableName;
7. 视图和存储过程
创建视图
sql">CREATE VIEW ViewName AS SELECT Column1, Column2 FROM TableName WHERE Condition;
删除视图
sql">DROP VIEW ViewName;
创建存储过程
sql">CREATE PROCEDURE ProcedureName AS BEGIN SELECT * FROM TableName; END;
执行存储过程
sql">EXEC ProcedureName;
8. 索引
创建索引
sql">CREATE INDEX IndexName ON TableName (ColumnName);
删除索引
sql">DROP INDEX IndexName ON TableName;
9. 事务控制
-
开始事务
sql">BEGIN TRANSACTION;
-
提交事务
sql">COMMIT;
-
回滚事务
sql">ROLLBACK;
10. 权限管理
授予权限
sql">GRANT SELECT ON TableName TO UserName;
撤销权限
sql">REVOKE SELECT ON TableName FROM UserName;
注意:在进行修改操作,如果对自己的sql没有把握可以先选择备份,在备份里面进行操作,或采用事物的方式(在修改前开启事物),以至于不会造成数据丢失以及损坏