您的位置:首页 > 数据库 > MySQL

C#开发用sql server(2008)与mysql(5.6) 的不同之处

2013-08-21 17:38 471 查看
C#开发用sql server(2008)与mysql(5.6) 的不同之处

程序方面

1 连接字符串

Sql server: connectionString="DataSource=IP;Initial Catalog=DBname;Persist Security Info=True;UserID=sa;Password=pwd;Max Pool Size = 512"

Mysql:connectionString="Server=127.0.0.1;Database=dbname;Uid=root;Pwd=pwd;charset=utf8;"

2 数据操作类库

Sql server: using System.Data.SqlClient;

Mysql: using MySql.Data.MySqlClient;(要下载mysql.data.dll)

3 调用存储过程区别(调用方式相同,有些小区别)

Sql server: 传参时参数名一般以@开头

Mysql: 参数不能以@开头,以?开头,存储过程的不用?开头,定义的参数名与存储过程一致即可,但不要与字段名相同



数据库部分

1 top 与limit

Sql server: select top n * from table orderby id desc;

Mysql: select * from table order by id desclimit n;



2 group by

Sql server: select itemcode,Avg(itemvalue)from table group by itemcode

Group by 部分须与select 部分一致,除非统计类用到的字段

Mysql: select itemcode,Avg(itemvalue) from table group by itemcode



3 日期函数很多不同,列出常用的一个

Sql server:convert(varchar(10),getdate(),120) 将时间转换成年-月-日 格式字符串

Mysql: DATE_FORMAT(NOW(),'%Y-%m-%d') mysql还有其它方式可以实现此功能



4 字符串相加

SqlServer 直接用 + 如 str1 + str2

MySql concat() 如 set str3 =concat(str1,str2);



5 存储过程写法

Sqlserver:

1 多个语句之间可以用;分隔,也可不用

2执行动态sql

Declare @strsql varchar(2000)

Set @strsql=’select * from table where id=@参数id’

Execute(@strsql);

3 Print @strsql 打印(显示)出执行的sql语句

4 exec(其它存储过程 参数1)

Mysql:

1多个语句之间必须用;分隔,查询里也一样

2 执行动态sql

Declare strSQL varchar(2000);

Set @strSQL2=concat(’select * from tablewhere id=’,’参数id’);

prepare strSQL from @strSQL2;

execute strSQL;

3 SELECT @strSQL2; 打印(显示)出执行的sql语句

4 call 其它存储过程(参数1)



6. isnull()

SqlServer isnull()

MySql ifnull()



7. getdate()

SqlServer getdate()

MySql now()



8. newid()

SqlServer newid()

MySql uuid()



9. @@ROWCOUNT

SqlServer @@ROWCOUNT

MySql row_count()

注意:MySql的这个函数仅对于update, insert, delete有效



10. SCOPE_IDENTITY()

SqlServer SCOPE_IDENTITY()

MySql last_insert_id()



11. if ... else ...

SqlServer IF Boolean_expression

Begin

sql_statement | statement_block

end

ELSE

Begin

sql_statement | statement_block

end

-- 单条语句可以不要BEGIN 和 END。

MySql

IFsearch_condition THEN statement_list

[ELSEIF search_condition THEN statement_list] ...

[ELSE statement_list]

END IF

注意:对于MySql来说,then, end if是必须的。类似的还有其它的流程控制语句,这里就不一一列出。



12. declare

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



13 游标的写法



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

selectProductId, Quantity from @tempShoppingCart

open tempCartCursor

fetch next from tempCartCursor into @productId, @quantity

while @@FETCH_STATUS = 0

begin

updateProduct set SellCount = SellCount + @quantity whereproductId = @productId



fetchnext 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 selectsectionid, newsid from _temp_SN;

declare continue handler for not found setm_done = 1;



create temporary table _temp_SN

selectsectionid, newsid from SectionNews groupby 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

--具体的处理逻辑

endif;

end while;

close _cursor_SN;

drop table _temp_SN;

注意:为了提高性能,通常在表变量上打开游标,不要直接在数据表上打开游标。



14. 分页的处理



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 byProductID 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 procedureGetProductsByCategoryId(

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

'selectsql_calc_found_rows * from product wherecategoryId = ? order by ProductId desc limit ?, ?';

execute PageSql using @categoryId, @startRow, @pageSize;

deallocate prepare PageSql;

set _totalRecCount = found_rows();



end



15 变量的定义及用法

sql server中变量要先申明后赋值:

局部变量用一个@标识,全局变量用两个@(常用的全局变量一般都是已经定义好的);

申明局部变量语法:declare @变量名数据类型;

例如:declare @num int;

赋值:有两种方法式(@num为变量名,value为值)

set @num=value; 或 select @num=value;

如果想获取查询语句中的一个字段值可以用select给变量赋值,如下:

select @num=字段名 from 表名 where ……



mysql中变量不用事前申明,在用的时候直接用“@变量名”使用就可以了。

第一种用法:set @num=1; 或set @num:=1; //这里要使用变量来保存数据,直接使用@num变量

第二种用法:select @num:=1; 或 select @num:=字段名 from 表名 where ……

注意上面两种赋值符号,使用set时可以用“=”或“:=”,但是使用select时必须用“:=赋值”

第三种用法用declare 声明变量,declare 语句必须放在所有语句的最上面,可以用set 赋值,也可以 select filedname from table into 声明的变量名 (此方式也适用于@变量;



16 临时表用法

Sql server:

--下面列的是变量表
declare
@curdayData table
(IDint,
ItemCode
int,
ItemValue
decimal,
IsDeal char(1))

Insert into
@curdayData select
ID ,ItemCode,ItemValue,'0'asIsDeal
From BaseEMData
whereIsFilter='0'andDataFlag='0'andDATEDIFF(day,samplingtime,getdate())=3orderby
ID desc

…略



Mysql:

#创建前如果表存在则先删除

DROP TABLE IF EXISTS tmp_table;

CREATE TEMPORARY TABLE tmp_table(ItemcodeINT,Itemvalue FLOAT,Isdeal char(1));

INSERTINTO tmp_table(Itemcode,Itemvalue,Isdeal) select ItemCode,max(ItemValue),'0'from SiteBaseEMData group by itemcode;

select * from tmp_table;

select@num:=count(1) from tmp_table;

while(@num>0)DO

set@num:=@num-1;

select@peritemcode:=itemcode from tmp_table where isdeal='0';

updatetmp_table set Isdeal='1' where itemcode =@peritemcode;

SELECT@peritemcode;



end WHILE;

select* from tmp_table;

dropTEMPORARY table tmp_table;



mysql临时表的限制:

临时表只能用在memory,myisam,merge,或者innodb

临时表不支持mysqlcluster(簇)

在同一个query语句中,你只能查找一次临时表。例如:下面的就不可用

mysql> SELECT * FROM temp_table, temp_table AS t2;

ERROR 1137: Can't reopen table: 'temp_table'



如果在一个存储函数里,你用不同的别名查找一个临时表多次,或者在这个存储函数里用不同的语句查找,这个错误都会发生。



show tables 语句不会列举临时表

你不能用rename来重命名一个临时表。但是,你可以alter table代替:

mysql>ALTER TABLE orig_name RENAME new_name;

临时表用完后要记得drop掉:

DROP TEMPORARY TABLE IF EXISTSsp_output_tmp;



17 备份数据库

Sqlserver:

BACKUP DATABASE @databasename TODISK
= @strPath
WITHNOINIT,
NOUNLOAD ,
NOSKIP,STATS
= 10,NOFORMAT

@databasename 数据库名

@strPath 备份的路径

Mysql:

string strsql =@"/c mysqldump-h192.168.1.1 -P3306 -uroot -proot --default-character-set=utf8 ISDB >E:\DBBack\" +DateTime.Now.ToString().Replace("-","").Replace(":","").Replace("//","").Replace("/","").Replace("\\","").Replace("
","")+ ".sql";

Process.Start("cmd.exe",strsql);

上例-uroot –u,root为用户名,后面类同,调用方式为c#



还原:mysql
-hlocalhost -P3306-uroot-p123
mydata <
d:\back\mydata.sql



18标示符限定符



SqlServer
[ ]
MySql
``
mysql注意事项:

1 如果要支持中文字符,在安装数据库的时候选用utf-8字符集;或在数据库表属性中更改



由于本人也是刚接触mysql方面的开发,很多用法并不一定对或者是最好的,请各位看到不妥的敬请指出,不胜感激
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐