问题
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
回答1:
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
回答2:
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...
回答3:
SELECT CONCAT('fldCode1',':','fldCode2') as Method;
回答4:
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' )
来源:https://stackoverflow.com/questions/17979909/concatenate-two-sql-fields-with-text