在连接时,是否有更简单的方法在整个字符串中添加字符?我正在考虑利用一个函数来做到这一点,并且可以通过串联来实现。但是,除了串联之外,还有其他方法可以完成吗?
这是我需要做的...表A有8列,在此示例中为col1,col2,col3等。
;WITH
TABLE_A
AS
(
SELECT 'ABC' AS Col1
, 'COM' AS Col2
, 'SMALL' AS Col3
, '1234' AS Col4
, 'ABC INC.' AS Col5
, '123456789' AS Col6
, 'ABC Of New England' AS Col7
, 'NC123456' AS Col8
)
SELECT *
FROM TABLE_A
我需要将各列中的值之间用>串联起来。我可以按照...
的方式完成此操作CONCAT(Col1,'>',Col2,'>',Col3,'>',Col4,'^',Col5,'>',Col6,'>',Col7,'>',Col8)
<',Col2,'>',Col3,'>',Col4,'^',Col5),依此类推,串联应该只在有值的地方进行。也要添加另一条皱纹,而不是在Col4和Col5之间添加>,我需要使用胡萝卜^作为分隔符。
是否有其他方法可以不使用CONCAT来执行此操作?可能是循环?
;WITH
TABLE_A
AS
(
SELECT 'ABC' AS Col1
, 'COM' AS Col2
, 'SMALL' AS Col3
, '1234' AS Col4
, 'ABC INC.' AS Col5
, '123456789' AS Col6
, 'ABC Of New England' AS Col7
, 'NC123456' AS Col8
)
SELECT ConcentenatedString = ISNULL(('>' + NULLIF(a.Col1,'')),'')
+ISNULL(('>' + NULLIF(a.Col2,'')),'')
+ISNULL(('>' + NULLIF(a.Col3,'')),'')
+ISNULL(('>' + NULLIF(a.Col4,'')),'')
+ISNULL(('^' + NULLIF(a.Col5,'')),'')
+ISNULL(('>' + NULLIF(a.Col6,'')),'')
+ISNULL(('>' + NULLIF(a.Col7,'')),'')
+ISNULL(('>' + NULLIF(a.Col8,'')),'')
FROM TABLE_A a
NULLIF
用于将空白字符串转换为NULL,以便在连接到NULL时将消除定界符。然后将这些NULL转换回空白,以防止删除字符串的其余部分。
CTEs
与嵌套的replace
一起使用。当^
和col4
不在col5
时,这也可以满足您的要求。当null
为>
时,我们还使用第二CTE处理前导col1
,但这是完全可选的。null
with cte1 as (select concat(col1,'>' ,col2,'>' ,col3,'>' ,col4, case when col4 is not null and col5 is not null then '^' else '>' end ,col5,'>' ,col6,'>' ,col7,'>' ,col8) as txt from your_table) ,cte2 as (select replace(replace(replace(txt,'>>>>','>'),'>>>','>'),'>>','>') as txt2 from cte1) select case when left(txt2,1)='>' then right(txt2, len(txt2)-1) else txt2 end as str from cte2;
;WITH
TABLE_A
AS
(
SELECT 'ABC' AS Col1
, 'COM' AS Col2
, 'SMALL' AS Col3
, '1234' AS Col4
, 'ABC INC.' AS Col5
, '123456789' AS Col6
, 'ABC Of New England' AS Col7
, 'NC123456' AS Col8
)
SELECT ConcentenatedString = ISNULL(('>' + NULLIF(a.Col1,'')),'')
+ISNULL(('>' + NULLIF(a.Col2,'')),'')
+ISNULL(('>' + NULLIF(a.Col3,'')),'')
+ISNULL(('>' + NULLIF(a.Col4,'')),'')
+ISNULL(('^' + NULLIF(a.Col5,'')),'')
+ISNULL(('>' + NULLIF(a.Col6,'')),'')
+ISNULL(('>' + NULLIF(a.Col7,'')),'')
+ISNULL(('>' + NULLIF(a.Col8,'')),'')
FROM TABLE_A a
NULLIF
用于将空白字符串转换为NULL,以便在连接到NULL时将消除定界符。然后将这些NULL转换回空白,以防止删除字符串的其余部分。