MYSQL与MSSQL常用用法区别

1、标识符限定符
SqlServer []
MySql “

2、字符串相加
SqlServer 直接用 +
MySql concat(),如:concat(‘my name is’,’jiajia’)

3、isnull()
SqlServer isnull()
MySql ifnull()或者COALESCE(),如:ifnull(insert_dt,0)或者COALESCE(start_dt,0)
注意:MySql也有isnull()函数,但意义不一样

4、获取系统当前时间
SqlServer getdate()
MySql now()

5、newid()
SqlServer newid()
MySql uuid()
注:MYSQL中不存在uniqueidentifier类型(一般用char(36)来代替处理),uuid()在建表时不能用作默认值,而MSSQL中却可以用newid()来做默认值。

6、@@ROWCOUNT
SqlServer @@ROWCOUNT
MySql row_count()
注:MySql的这个函数仅对于update, insert, delete有效,而对于select 则用FOUND_ROWS()。其中,当update更新值与原字段值相同时,此时row_count()值为0,这点需引起注意,对于这种情况,需先判断表中是否存在数据的情况。

7、SCOPE_IDENTITY()
SqlServer SCOPE_IDENTITY()
MySql last_insert_id()

8、if……else……
SqlServer:
IF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]

– 若要定义语句块,请使用控制流关键字 BEGIN 和 END。
MySql:
IF (search_condition)
THEN statement_list
[ELSEIF search_condition THEN statement_list]…
[ELSE statement_list]
END IF;
注意:对于MySql来说,then, end if是必须的。类似的还有其它的流程控制语句,这里就不一一列出。

9、declare声明局部变量
其实,SqlServer和MySql都有这个语句,用于定义变量,但差别在于:在MySql中,DECLARE仅被用在BEGIN ……END复合语句里,并且必须在复合语句的开头,在任何其它语句之前。这个要求在写游标时,会感觉很BT。

10、游标的写法
SqlServer中:
declare @tempShoppingCart table (ProductId int, Quantity int)
insert into @tempShoppingCart (ProductId, Quantity)
select ProductId, Quantity from ShoppingCart where UserGuid = @UserGuid
declare @productId int
declare @quantity int
declare tempCartCursor cursor for
select ProductId, Quantity from @tempShoppingCart
open tempCartCursor
fetch next from tempCartCursor into @productId, @quantity
while @@FETCH_STATUS = 0
begin
update Product set SellCount = SellCount + @quantity where productId = @productId
fetch next from tempCartCursor into @productId, @quantity
end
close tempCartCursor
deallocate tempCartCursor

MySql中:
declare m_done int default 0;
declare m_sectionId int;
declare m_newsId int;

declare _cursor_SN cursor for select sectionid, newsid from _temp_SN;
declare continue handler for not found set m_done = 1;
create temporary table _temp_SN
select sectionid, newsid from SectionNews group by sectionid, newsid having count(*) > 1;
open _cursor_SN;
while( m_done = 0 ) do
fetch _cursor_SN into m_sectionId, m_newsId;
if( m_done = 0 ) then
– 具体的处理逻辑
end if;
end while;
close _cursor_SN;
drop table _temp_SN;
注意:为了提高性能,通常在表变量上打开游标,不要直接在数据表上打开游标。

11、分页的处理
SqlServer:
create procedure GetProductByCategoryId(
@CategoryID int,
@PageIndex int = 0,
@PageSize int = 20,
@TotalRecords int output
)
as
begin
declare @ResultTable table
(
RowIndex int,
ProductID int,
ProductName nvarchar(50),
CategoryID int,
Unit nvarchar(10),
UnitPrice money,
Quantity int
);

insert into @ResultTable
select row_number() over (order by ProductID asc) as RowIndex,
p、ProductID, p、ProductName, p、CategoryID, p、Unit, p、UnitPrice, p、Quantity
from Products as p
where CategoryID = @CategoryID;
select @TotalRecords = count(*) from @ResultTable;
select *
from @ResultTable
where RowIndex > (@PageSize * @PageIndex) and RowIndex <= (@PageSize * (@PageIndex+1));
end;
当然,SqlServer中并不只有这一种写法,只是这种写法是比较常见而已。

MySql:
create procedure GetProductsByCategoryId(
in _categoryId int,
in _pageIndex int,
in _pageSize int,
out _totalRecCount int
)
begin
set @categoryId = _categoryId;
set @startRow = _pageIndex * _pageSize;
set @pageSize = _pageSize;

prepare PageSql from
‘select sql_calc_found_rows * from product where categoryId = ? order by ProductId
desc limit 2;
execute PageSql using @categoryId, @startRow, @pageSize;
deallocate prepare PageSql;
set _totalRecCount = found_rows();
end

12、MYSQL存储过程中声明局部变量,并为其赋值。
declare var_name type [default value];
select filed_name into var_name from table_name;
另一种赋值方法:
select @str:=fild_name from table_name limit 1;
select @str;

13、查询存储过程的创建脚本
show create procedure pr_name;

14、查询表的创建脚本
show create table tab_name;

15、显示数据库中所有存储的存储过程基本信息,包括所属数据库,存储过程名称,创建时间等
show procedure status;

16、建表脚本中的自增列
MYSQL:AUTO_INCREMENT

MSSQL:IDENTITY(1,1)

17、时间类型
MYSQL:TIMESTAMP

MSSQL:DATETIME

18、date_add()函数
MYSQL:DATE_ADD(NOW(),INTERVAL 2 DAY); 或者 TIMESTAMPADD(DAY,2,NOW());

MSSQL:DATEADD(dd,2,getdate());

19、TIMESTAMPDIFF函数
MYSQL:TIMESTAMPDIFF(DAY,’2013-03-19’,NOW());

MSSQL:datediff(dd,startdate,enddate);

20、执行存储过程
MYSQL:CALL PR_NAME(PARA1,PARA2,…);

MSSQL:exec pr_name para1,para2,…;

21、convert()函数
MYSQL:CONVERT(value,type);如:CONVERT(NOW(),char(20))
其中type支持类型如下:
二进制,同带binary前缀的效果:BINARY
字符型,可带参数: CHAR()
日期: DATE
时间: TIME
日期时间型: DATETIME
浮点数: DECIMAL
整数: SIGNED
无符号整数: UNSIGNED

MSSQL:convert(varchar(20),getdate(),20);

22、获取本月第一天
格式为:YYYY-MM-DD
MYSQL:select DATE_ADD(curdate(),interval -day(curdate())+1 day);
MSSQL:select convert(varchar(10),dateadd(dd,-day(getdate())+1,getdate()),120);
格式为:YYYYMMDD
MYSQL:select DATE_FORMAT(DATE_ADD(curdate(),interval -day(curdate())+1 day),’%Y%m%d’);
MSSQL:select convert(varchar(10),dateadd(dd,-day(getdate())+1,getdate()),112);

23、获取本月最后一天
格式为:YYYY-MM-DD
MYSQL:select DATE_ADD(DATE_ADD(curdate(),INTERVAL 1 MONTH),interval -day(curdate()) day);
MSSQL:select convert(varchar(10),dateadd(dd,-day(getdate()),dateadd(m,1,getdate())),120)
格式为:YYYYMMDD
MYSQL:select DATE_FORMAT(DATE_ADD(DATE_ADD(curdate(),INTERVAL 1 MONTH),interval -day(curdate()) day),’%Y%m%d’);
MSSQL:select convert(varchar(10),dateadd(dd,-day(getdate()),dateadd(m,1,getdate())),112)

24、判断某个变量或表达式是否为数值
由于MYSQL中没有像MSSQL中isnumeric函数来判断一个字符串中是否字符,因此只好通过自定义函数来实现类似的函数功能。
MYSQL:
创建自定义函数的脚本为:
– 返回0表示为非数值或含有非数值字符,返回1表示为数值
CREATE FUNCTION ISNUMERIC(myVal VARCHAR(1024))
RETURNS TINYINT(1) DETERMINISTIC
RETURN myVal REGEXP ‘^(-|\+)?([0-9]+\.[0-9]|[0-9]\.[0-9]+|[0-9]+|[0-9]+\.[0-9]e\+[0-9]+|[0-9]\.[0-9]+e\+[0-9]+|[0-9]+e\+[0-9]+)$’;

MSSQL:select isnumeric(expression)=0(表示 expression 中含有字符,反之为数值)

25、错误及异常处理
由于MYSQL中没有类似MSSQL中@@error的函数来捕捉执行sql语句时产生的错误或异常,所以需要采用一些替代方法来实现。当然你也可以通过查询@@error_count和@@warning_count(如:select @@error_count,@@warning_count)来达到判断的目的,但warning_count 的值可能会比 SHOW WARNINGS 显示的结果记录数大,因为系统变量 max_error_count 被设置的比较小,因此没有把所有的信息都存下来。
例如:
DECLARE _err int default 0;
DECLARE continue handler for sqlexception, sqlwarning, not found set _err=1;

MYSQL:
MYSQL中异常及错误捕捉测试存储过程如下:
DROP PROCEDURE IF EXISTS pr_testerror;
CREATE PROCEDURE pr_testerror(
)
proc_start:BEGIN

DECLARE _err int default 0;
DECLARE continue handler for sqlexception, sqlwarning, not found set _err=1;
INSERT INTO persons(name,age,tel,edate,sex)
SELECT ‘juanzi’,22,18729273781,NOW(),f;
IF _err=1
THEN
LEAVE proc_start;
END IF;
END proc_start

MSSQL:select @@error 或者if (@@error<>0 )… 来捕捉错误及异常。

26、延时时间处理
MYSQL:SLEEP(5); 表示延时5秒钟。测试:SELECT SYSDATE(),SLEEP(5),SYSDATE();
MSSQL:waitfor delay ‘00:00:03’; 表示延时3秒钟,另外,waitfor time ‘11:20:46’;表示等到11点20分46秒后才执行。

27、取日期单独部分
MYSQL:SELECT DATE_FORMAT(NOW(),’%Y’);
MSSQL:select datepart(yy,getdate());

28、判断表是否存在
MYSQL:if exists(select 1 from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA=’db_name’ and TABLE_NAME=’table_name’);
MSSQL:if exists(select 1 from sysobjects where id=object_id(‘db_name.table_name’) and type=’U’);

29、循环中的中断和继续处理
MYSQL:break用LEAVE处理,continue用iterate处理。如:whl1:while … do …break whl1…end while whl1;
MSSQL:用break和continue直接处理。

30、FULL OUTER JOIN
目前MYSQL暂时还不支持full outer join的联接操作,等待后面的版本会支持该操作。
MYSQL:
涉及两个表时(需求实现如select a.col1,b.col2 from t1 a full outer join t2 b on a.id=b.id):
select a.col1,b.col2 from t1 a left join t2 b on a.id=b.id
union
select a.col1,b.col2 from t1 a right join t2 b on a.id=b.id
涉及三个表时(需求实现如select a.col1,b.col2,c.col3 from t1 a full outer join t2 b on a.id=b.id full outer join t3 c on b.id=c.id):
select a.col1,b.col2,c.col3 from t1 a left join t2 b on a.id=b.id left join t3 c on b.id=c.id
union
select a.col1,b.col2,c.col3 from t1 a right join t2 b on a.id=b.id left join t3 c on b.id=c.id
union
select a.col1,b.col2,c.col3 from t1 a right join t2 b on a.id=b.id right join t3 c on b.id=c.id;

MSSQL:select a.col1,b.col2 from employee a full outer join master b on a.id=b.id;

31、实现将某一字段值以逗号分隔成一行
MYSQL: SELECT uid,GROUP_CONCAT(name SEPARATOR ‘,’) FROM persons;
动态行转列示例:
SET @EE=”;
SELECT @EE:=GROUP_CONCAT(@EE,’sum(if(zone=\”,zone,’\”,’,tel,0)) as ‘,””,zone,””) from (select DISTINCT zone from t_tmp)a;
SET @str=CONCAT(‘select ‘,@EE,’ from t_tmp group by tel’);
PREPARE stmt from @str;
EXECUTE stmt;

MSSQL:
declare @tt varchar(300)
select @tt=”
select @tt=@tt+name+’,’ from persons
select @tt

32、定时执行作业计划
MYSQL: 通过事件(event)来实现定时执行作业计划,但需要保证事件调度器的正常启用。
MSSQL: 通过作业(job)来实现定制执行作业计划,但需要保证代理服务器正常启用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章