好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

深入讲解SQL中的字符串拼接

一、概述

相信大家在日常开发中,在sql语句中经常需要进行字符串拼接,以sqlserver,oracle,mysql三种数据库为例,因为这三种数据库具有代表性。

sqlserver:

?

1

select '123' + '456' ;

oracle:

?

1

select '123' || '456' from dual;

?

1

select concat( '123' , '456' ) from dual;

mysql:

?

1

select concat( '123' , '456' );

注意: sql server中没有concat函数(sql server 2012已新增concat函数)。oracle和mysql中虽然都有concat,但是oracle中只能拼接2个字符串,所以建议用||的方式;mysql中的concat则可以拼接多个字符串。

在sql server中的[+]号除了能够进行字符串拼接外,还可以进行数字运算,在进行字符串拼接时要小心使用。下面以[users]表为例,进行详细分析:

二、数字 + 字符串

2.1 int + varchar

?

1

2

select id + place from users where id = 1; //提示错误[在将 varchar 值 'bzz' 转换成数据类型 int 时失败]

select id + place from users where id = 5; //提示错误[在将 varchar 值 '102.34' 转换成数据类型 int 时失败]

?

1

select id + place from users where id = 4; //返回 int [105]

2.2 decimal + varchar

?

1

select *, id + cost from users where id = 4 or id = 5; //返回 decimal [102.98]和[104.30]

?

1

select *, place + cost from users where id = 1; //提示错误[从数据类型 varchar 转换为 numeric 时出错。]

由此可见,系统会将字符串varchar类型转化为int,若不能转换则提示错误,转换成功则进行数字计算。

三、数字 + 数字

数字指的是int、decimal等类型。数字 +  数字,则进行数字相加,若某字段为null,则计算结果为null。

?

1

select *, uage + cost as 'uage + cost' from users

四、字符串 + 字符串

字符串 + 字符串,则直接进行拼接。若某字段为null,则计算结果为null。

?

1

select *, uname + place as 'uname + place' from users

五、使用cast和convert函数进行类型转换

通过上述实例,可以看出若要使用[+]进行字符串拼接或数字计算,最稳妥的方法是进行类型转换。

cast() 函数可以将某种数据类型的表达式转化为另一种数据类型 convert() 函数也可以将制定的数据类型转换为另一种数据类型

要求: 将[678]转化为数值型数据,并与123相加进行数学运算。

?

1

2

select cast ( '678' as int ) + 123;

select convert ( int , '678' ) + 123;

要求: id列和place列进行字符串拼接。

?

1

select *, convert ( varchar (10), id) + place from users;

字符串拼接后的字符串不能简单作为[筛选字段]

有时,需要列a = 变量1,列b = 变量2的筛选,为了简化sql语句 列a + 列b = 变量1 + 变量2。这种方法并不完全准确

?

1

select * from users where uname + place = 'aabzz' ;

?

1

select * from users where uname = 'aa' and place = 'bzz' ;

为了防止上述情况的发生,可以再列a和列b之间加上一个较特殊的字符串。

?

1

select * from users where uname + 'rain@&%$man' + place = 'aa' + 'rain@&%$man' + 'bzz'

总结

以上就是关于sql中字符串拼接的全部内容了,希望本文的内容对大家的学习或者使用sql能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:http://HdhCmsTestcnblogs测试数据/rainman/p/6203065.html

查看更多关于深入讲解SQL中的字符串拼接的详细内容...

  阅读:77次