简体   繁体   中英

Concatenate two SQL fields with text

How can I concat two fields and text in between? I've tried all of the following and nothing has worked...

([fldCode1] || ':' ||[fldCode2]) AS Method

([fldCode1] + ':' + [fldCode2]) AS Method

([fldCode1] & ':' & [fldCode2]) AS Method
                                                *** & cannot be used with varchar 

This should work

select [fldCode1] + ':' + [fldCode2]
from tab

or if the columns are numeric

select cast([fldCode1] as varchar(100)) + ':' + cast([fldCode2] as varchar(100))
from tab

The first and last forms are not valid, but the second is certainly ok, assuming the columns are strings. If the columns are numeric, date etc. you will need to convert them first:

SELECT Method = CONVERT(VARCHAR(255), fldCode1)
        + ':' + CONVERT(VARCHAR(255), fldCode2)
FROM ... 

If they're strings and the following does not work:

SELECT Method = fldCode1 + ':' + fldCode2 FROM ...

Then you need to better define what "does not work" means...

SELECT CONCAT('fldCode1',':','fldCode2')作为方法;

Starting with 2008 SQL SERVER 2008 (don't forget to use ISNULL function else your result will be null) if you try to concattenate null column.

SELECT ISNULL('myFirstString', '') + ' ' + ISNULL('mySecondString', '')

You can also set CONCAT_NULL_YIELDS_NULL to off this way if you don't want to use ISNULL function so this will work.

SET CONCAT_NULL_YIELDS_NULL OFF
SELECT 'myFirstString' + ' ' + 'mySecondString'

Starting with SQL SERVER 2012 It's as simple as that

SELECT CONCAT ( 'Happy ', 'Birthday ', 11, '/', '25' )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM