The syntax difference between mysql and "sql server": 1. Mysql supports enum and set types, but "sql server" does not; 2. Mysql's increment statement is "AUTO_INCREMENT", while "sql server"'s It is identity; 3. The default value of "sql server" for table creation statements is "((0))", and two parentheses are not allowed in mysql.
The operating environment of this tutorial: windows10 system, mysql8.0.22 version, Dell G3 computer.
What is the difference between the syntax of mysql and sql server
Detailed introduction:
For many people, learn MySQL first and then SQLServer For beginners, one of the most uncomfortable things is that there are some subtle differences in the syntax between the two that make it difficult to adapt. For example, there are no keywords such as modify and change in SQL Server, or every keyword in MySQL A statement ends with ;
, but SQLServer uses the keyword go
to indicate the end of a batch statement, etc...
This article is exactly In this case, I hope to help people who are learning both SQL languages understand the syntax of these two databasesDIFFERENCE
Basic Grammar
Note: The syntax of comments in the two databases is the same, example:
# 单行注释-- 单行注释(注意是杠杠空格)/* 多行注释 */
-
End of statement:
In MySQL,
;
must be used to separate each statement and serve as the end of the statement. When multiple statements are executed together, an error will be reported if the statements are not separated by semicolonsExample:
use Student; -- 同时运行俩条语句时不用;分隔语句会报错select * from SC;
The semicolon is optional in SQLServer. You can choose to add it or not. At the same time, SQLServer provides go
keyword, as the end of a batch statement, it is recommended to use go
when writing SQL Server. This way, a batch error will not be reported when the next statement requires the previous statement to be executed before it can be executed. Example:
use Student-- 假设SC数据表在Student库下,此时如果不写go会报错goselect * from SC
-
Storage engine:
Commonly used storage engines in mysql include InnoDB | MyISAM | MEMORY | MERGE and other storage engines, among which InnoDB is the most used
In SQLServer, database storage is divided into logical implementation and physical implementation. Schematic diagram:
- MySQL can use single quotes and double quotes, while SQLServer only supports single quotes
- are not strictly case-sensitive
- Locate a certain tablemysql: library name. table name, example: Student.SCSQLServer :Library name.dbo.Table name or library name...Table namewhere dbo is the database owner (Database Owner), that is, the user who has permission to access the database is the only one who has all permissions for this database. And can provide access rights and functions to other usersExample:
Student.dbo.SC -- 或者: Student..SC
- Exec keyword in SQLServer:
-- 1. exec 存储过程名 参数1, 参数2....-- 注意:执行存储过程时是不加括号的 -- 2. exec('sql语句'),表示执行该语句
- SQLServer advanced syntax provides a series of sp commands
- System database in SQLServer:master: Record all system-level information of the systemmodel: template databasemsdb: storage plan information, backup and recovery related information, SQLServer agent scheduling alarms and job scheduling and other informationtempdb: Temporary database, which provides storage space for all temporary tables, temporary stored procedures and all other temporary operations resource: Hidden read-only database, containing all system objects, but does not contain user data or users Original data
- System database in mysql:information_schema: Provides a way to access database metadata. (Metadata is data about the data, such as database or table names, column data types, or access permissions. Other terms sometimes used to describe this information include "data dictionary" and "system catalog") Information about all other databases maintained by the MySQL server, such as database name, database tables, table column data types and access permissions, etc.In INFORMATION_SCHEMA, there are several read-only tables. They are actually views, not basic tablesmysql: core database (similar to the master table of SQL Server), which stores the control and management information that mysql needs to use, such as users, permission settings, keywords, etc. of the database. For example, to change the root user password, you need to use this databaseperformance_schema;sys;
- When the load pressure is the same, the memory and CPU consumed by MySQL Less
- The print statement print is also provided in SQLServer, but not in mysql, example:
-- print自带换行 print 'hello'
MySQL支持enum和set类型,SQLServer不支持
DDL&DML语句
建库
mysql:
-- 直接创建即可CREATE DATABASE [IF NOT EXISTS] 数据库名 [character set 字符集名];
SQLServer:
/* 除了数据库名字外还需要指定: 主数据文件逻辑名(一般与数据库同名),主数据物理文件名称(.mdf) 主数据文件初始大小(默认5MB),最大容量,增长速度 日志文件逻辑名(一般命名为库名字_log),日志物理文件名(.ldf) 日志文件初始大小(默认1MB),最大容量,增长速度 是否加上次要数据文件(.ndf),是否在增加几个日志文件.... 并且逻辑文件命名需要与物理文件命名相对应 主数据文件逻辑默认名为数据库名 */-- 示例:CREATE DATABASE 数据库名[ON [PRIMARY]( NAME = 'test', FILENAME='D:\test.mdf', [SIZE=10240KB/MB/GB/TB, ] [MAXSIZE = UNLIMITED/20480KB/MB/GB/TB,] [FILEGROWTH = 10%/1024KB/MB/GB/TB])][LOG ON ( NAME='test_log', FILENAME='D:\test_log.ldf', [SIZE=1024KB/MB/GB/TB,] [MAXSIZE = 5120KB/MB/GB/TB/UNLIMITED,] [FILEGROWTH = 1024KB/MB/GB/TB/%])]GO/* 其中: ON表示后面定义的是数据文件 ON PRIMARY表示定义主数据文件 LOG ON表示定义日志文件 NAME表示文件逻辑名 FILENAME表示文件物理名 SIZE表示初始大小,至少为模板数据库model的大小(主数据文件与日志文件分别是3M与1M) MAXSIZE表示文件最大大小,可以为UNLIMITED(无限制) FILEGROWTH表示文件大小增长速度,默认值10%,每次最少增加64kb 默认单位都是MB 注意:括号中最后一行无逗号,其他行都需要逗号 */
查看库
打开指定库(一致)
俩者语法一致,都是use 库名
查看所有数据库
mysql:
-- 查看当前所有数据库: show databases; -- 查询某个数据库的字符集(查询数据库的创建语句即可实现): show create database name;
SQLServer:
-- 查看当前所有数据库: select name, database_id, create_date from sys.databases go -- SQLServer中的数据库信息存储在sys.databases中 -- 表示查询数据库名字,数据库id与创建时间,固定写法 -- 查看数据库信息 sp_helpdb 数据库名 go
修改库
注意:不管是哪种数据库,修改库的信息我们都是很少做的
mysql:
-- 对数据库重命名 RENAME DATABASE 数据库旧名 TO 数据库新名; -- 修改数据库的字符集 ALTER DATABASE 数据库名 CHARACTER SET 字符集名;
SQLServer:
-- 对数据库重命名sp_renamedb oldname, newname go-- 待补充
删除库(一致)
语法:
DROP DATABASE [IF EXISTS] 数据库名;
建表
最大容量
SQLServer每个表最多能有1024列,每行最多允许有8060个字节
MySQL一个表的总字段长度不能超过65535
建表语法(基本一致)
为什么说是基本一致呢,因为在SQLServer建表中,可以通过在表名前面加上db_name.dbo的形式来指定所属数据库与所有者,而在mysql中我暂时是没看到类似语法的
语法:
CRATE TABLE [IF NOT EXISTS] 表名( 列名 列的类型[(长度) 约束], 列名 列的类型[(长度)约束], 列名 列的类型[(长度)约束], ... 列名 列的类型[(长度)约束] ); -- 注: -- 约束是可选项,不一定要填写 -- 最后一列的后面不需要添加逗号,其他每一列都需要添加逗号 -- SQLServer中不能通过这种IF NOT EXISTS的形式判断是否存在 -- SQLServer中的所有判断是否存在都只能通过IF EXISTS(查询语句)的方法实现 -- 检查表是否存在示例: IF EXISTS(select count(*) from dbo.sysobjects where name = 'table_name') go -- 检查字段是否存在示例: IF EXISTS(select count(*) from dbo.syscolumns where id = object_id('table_name') and name = 'column_name') go -- 或者: if DB_ID('name') is not null -- 不存在 create TABLE....
查看表
mysql:
-- 查询数据库中所有表(SQLServer没有): show tables [from 数据库名; -- 查看表结构(SQLServer没有) desc 表名; # 查看指定表下的数据结构 -- 使用database()函数查看当前处于哪个数据库(SQLServer没有) select database();
SQLServer:
-- 查询当前数据库内所有表,固定写法 select * from sysobjects where xtype = 'U' -- 查看表结构 sp_help 表名; -- 或者: sp_columns 表名; -- 也可以在前面加上exec
修改表
修改表名
mysql:
ALTER TABLE name rename [to] newName;
SQLServer:
exec sys.sp_rename
修改语句
SQLServer中没有change与modify语句,因此SQLServer使用俩个alter
删除表
基本一致
分离与附加数据库:
SQLServer:
-- 分离数据库 sp_detach_db 数据库名 go -- 附加数据库 exec sp_attach_db [@dbname = ]'数据库名', [@filename1 = ]'包含路径的文件物理名'[...16] go -- 数据库文件最多可以指定16个
约束/索引
递增语句MySQL是AUTO_INCREMENT,SQLServer是identify(10.1),从10开始一次加1
mysql不支持检查索引(check),SQLServer支持
数据类型
MySQL中没有nchar,nvarchar,ntext等类型
-
SQLServer使用datetime类型作为获取默认值为当前时间的数据类型
而MySQL使用timestamp时间错类型实现这个效果
MySQL支持无符号的整数类型,而SQLServer不支持
DQL语句
查询前几条记录:
SQLServer提供了top关键字
而MySQL使用limit关键字
示例:
select * from Student limit 100;select top 100 * from Student;
全外连接
mysql 不支持 直接写full outer join 或者 full join 来表示全外连接但是可以用union联合查询 代替
而SQLServer支持全外连接
其余查询语法基本一致
常见函数
调用函数方法
MySQL与SQLServer调用函数都是使用select调用函数,示例:
SELECT 函数名(参数列表);
获取当前时间
MySQL可以使用current_date()函数获取当前日期,或者使用CURRENT_TIME()函数只获取当前时间,或者使用CURRENT_TIMESTAMP()函数与now()函数获取当前的完整时间,示例:
SELECT CURRENT_DATE(); -- 2021-12-27 SELECT CURRENT_TIME(); -- 01:42:23 SELECT CURRENT_TIMESTAMP(); -- 2021-12-27 01:42:23 SELECT NOW(); -- 2021-12-27 01:42:23
而SQLServer可以使用getdate()方法获取当前时间日期,示例:
SELECT getdate(); -- 返回值:2021-12-27 01:40:40.907
判空函数
mysql:
-- 1. ifnull(exp1,exp2); -- 表示当exp1为空时值为exp2,不为空时值为exp1 -- 2. isnull(exp1); -- 当exp1为空时返回1,不为空时返回0 -- 3. 同时在MySQL中还提供了if函数(与if结构语句不同),示例: if (exp1,exp2,exp3) -- 表示当条件表达式exp1成立时返回exp2.否则返回exp3 -- 类似于java中的三目表达式,SQLServer中没有这个函数
SQLServer:
-- 1. isnull(exp1,exp2); -- 表示当exp1为空时值为exp2,不为空时值为exp1 -- 没有ifnull()函数 -- 相对来说mysql的ifnull和isnull函数容易理解一点
字符串连接函数
mysql:
-- 使用concat()函数,示例:SELECT CONCAT('我','在','学习mysql');-- 不能使用+连接字符串!
SQLServer:
-- 1. 使用加号+连接字符串 select 'hello'+'SQL' -- 2. 使用concat()函数,示例: SELECT CONCAT('我','在','学习mysql');
流程控制结构
IF结构
mysql需要在if 条件后以及else后添加then再写语句
并且mysql中的IF结构只能写在begin end块中
语法:
-- 语法IF 条件1 THEN 语句1;ELSEIF 条件2 THEN 语句2;...ELSE 语句n;END IF; -- 表示IF结构结束了-- 注释:只能用于BEGIN END块中-- 语句中只有一条时可以省略begin end
而在SQLServer中不需要写then
语法:
IF (条件1)BEGIN 语句1ENDelseBEGIN 语句2ENDgo-- 示例:IF (EXISTS (select Sno from Student where Sno = '200001')) select Sno from Student where Sno = '200001'ELSE print '没有改学生'go
case结构(一致)
都需要使用then
不需要写Begin,只需要写END,分为俩种形式:
case后可以带一个值,在when中通过判断这个值的取值来达到选择效果(switch-case形式)
也可以不带值,在when语句中写条件判断式(多重IF形式)
语法:
-- 1: case 要判断的字段或表达式 when 常量1 then 要显示的值1或语句1 when 常量2 then 要显示的值2或语句2 ... else 要显示的值n或语句n end -- 2: case when 条件1 then 要显示的值1或语句1 when 条件2 then 要显示的值2或语句2 ... else 要显示的值n或语句n end
循环结构
基本一致
但是在MySQL中在while循环后面需要加上do关键字
同时在end后面需要写上循环类型与循环表示,例如:WHILE [标签];
SQLServer不用
视图
mysql视图中的from子句不允许存在子查询,而SQLServer支持
推荐学习:mysql视频教程
The above is the detailed content of What is the difference between the syntax of mysql and sql server?. For more information, please follow other related articles on the PHP Chinese website!

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

SQL commands in MySQL can be divided into categories such as DDL, DML, DQL, DCL, etc., and are used to create, modify, delete databases and tables, insert, update, delete data, and perform complex query operations. 1. Basic usage includes CREATETABLE creation table, INSERTINTO insert data, and SELECT query data. 2. Advanced usage involves JOIN for table joins, subqueries and GROUPBY for data aggregation. 3. Common errors such as syntax errors, data type mismatch and permission problems can be debugged through syntax checking, data type conversion and permission management. 4. Performance optimization suggestions include using indexes, avoiding full table scanning, optimizing JOIN operations and using transactions to ensure data consistency.

InnoDB achieves atomicity through undolog, consistency and isolation through locking mechanism and MVCC, and persistence through redolog. 1) Atomicity: Use undolog to record the original data to ensure that the transaction can be rolled back. 2) Consistency: Ensure the data consistency through row-level locking and MVCC. 3) Isolation: Supports multiple isolation levels, and REPEATABLEREAD is used by default. 4) Persistence: Use redolog to record modifications to ensure that data is saved for a long time.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment