首先先放两个存储过程来进行对比
CREATE DEFINER=`root`@`%` PROCEDURE `searchProduct`( IN cone VARCHAR ( 30 ), IN ctow VARCHAR ( 30 ), IN page INT, IN size INT ) BEGIN set @s='SELECT * FROM productclass where status=0'; -- if(pname is not null) and pname!='' -- then set @s=concat(@s,' and product LIKE \'','%',pname,'%','\''); -- end if; if(cone is not null) and cone!='' then set @s=concat(@s,' and class1 LIKE \'','%',cone,'%','\''); end if; if(ctow is not null) and ctow!='' then set @s=concat(@s,' and class2 LIKE \'','%',ctow,'%','\''); end if; set @s=concat(@s,' ORDER BY class1,class2,class3,class4'); if(size>0) then set @s=concat(@s,' limit ',(page-1)*size,',',size); end if; -- 拼接完成后可以调用 select @s 语句,查看最终拼接的sql语句是否正确 prepare stmt from @s;-- 预编译一条sql语句,并命名为stmt execute stmt;-- 执行预编译sql END
ALTER PROCEDURE [dbo].[searchProduct] @cone VARCHAR ( 30 ),@ctow VARCHAR ( 30 ),@page INT,@size INT AS BEGIN -- routine body goes here, e.g. -- SELECT 'Navicat for SQL Server' declare @s Nvarchar(MAX); set @s='SELECT * FROM productclass where status=0'; -- if(pname is not null) and pname!='' -- then set @s=concat(@s,' and product LIKE \'','%',pname,'%','\''); -- end if; if(@cone is not null) and @cone!='' BEGIN set @s=concat(@s,' and class1 LIKE ','''%',@cone,'%'''); END if(@ctow is not null) and @ctow!='' BEGIN set @s=concat(@s,' and class2 LIKE ','''%',@ctow,'%'''); END set @s=concat(@s,' ORDER BY class1,class2,class3,class4'); if(@size>0) BEGIN set @s=concat(@s,'( select top ',@size,' id from productclass where id not in ( select top ', (@page-1)*@size,' id from productclass ))') END -- 拼接完成后可以调用 select @s 语句,查看最终拼接的sql语句是否正确 print(@s) EXEC sp_executesql @s; END
综合以上同一功能函数在不同的数据库中的规则不同,总结如下几点区别与相互之间的转换规则:
(1)对于输入参数来说
注意对于参数在下面语句使用中,mysql可以直接使用名称,二sqlserver要加上@符号
(2)对于语句的set来说
(3)对于if语句的执行
(4)对于定义sql语句的执行
注意:sqlserver也可以使用exec(@s),这样的话变量声明一般是varchar类型,若使用sp_executesql必须是Nvarchar的定义类型,具体的区别可以自行百度查询
总体来说,sql sever和Mysql的存储过程的思路都是一样的,但是在语法和结构上还是有很大的区别的,可以使用如下的转换方式。
CREATE proc p1 aa int bb varchar(255) output as | CREATE PROCEDURE p1( in aa int, out bb varchar(255) ) begin statement_list end; |
GO | delimiter $$ |
smalldatetime | datetime |
money | DECIMAL(18,4) |
numeric | DECIMAL |
max | 8000 |
isnull | ifnull |
getdate | now |
dbo. |
select 'sunday' day; | SELECT 'sunday' AS day; |
if condition statement else statement | if condition then statement else statement end if; |
目标类型可以是任意类型 | 目标类型可以是以下类型之一:BINARY,CHAR,DATE,DATETIME,TIME,DECIMAL,SIGNED,UNSIGNED |
exec(@sql) | PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; |
exec p1 @v1,@v2,@v3 output | call p1(hy_v1,hy_v2,@v3 output ); |
select 表字段 into #临时表名称 from 正常表 | CREATE TEMPORARY TABLE IF NOT EXISTS 临时表名称 AS SELECT 表字段名称 FROM 表名称; |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。