I want to concatenate column values with a separator and assign it to variable.
If column value is null
, there's no need to add separator.
For example: A|B|C|D
If B is null A|C|D
.
I tried with CONCAT
function, but if B is null, it results in A||C|D
DECLARE @OldValue VARCHAR(8000);
SELECT @OldValue = CONCAT([FloorCode],'|',
[FloorName],'|',
[BuildingID],'|',
[HCMLocationCode],'|',
[IsActive])
FROM tblFloor_Master
WHERE FloorID = @FloorID;
@FloorID
is an input parameter of SP
5条答案
按热度按时间kb5ga3dv1#
ct3nt3jp2#
You can try the following query.
The output is as shown below
If you do not want to put space between values then you can try this
In this case the output will be
You can also try the below actual query using stored procedure
Live demo here - Live Demo
j5fpnvbx3#
Should be simple as doing
replace
, replace || to | then replace ||| to | since the maximum number of | is 3.inkz8wg94#
SELECT TRIM ('|' FROM regexp_replace( CONCAT('','|','COLB','|','','|','COLD','|','COLE') ,'[|]+' ,'|' ,'g' ) )
pod7payv5#
I've only just discovered it too, but the
CONCAT_WS
(With Separator) function is designed for this problem. It has been available since SQL Server 2017.