我需要从表的7个不同列连接,每列的文本之间用连字符。
在少数情况下列有空值,
我得到字符串; --Account--stands---
所需的输出为Account-stands
。请帮忙。
此致 Sajan
答案 0 :(得分:1)
在SQL Server中,您可以执行以下操作:
select stuff(coalesce('-' + col1, '') +
coalesce('-' + col2, '') +
coalesce('-' + col3, '') +
coalesce('-' + col4, '') +
coalesce('-' + col5, '') +
coalesce('-' + col6, '') +
coalesce('-' + col7, ''),
1, 1, '')
许多其他数据库支持像CONCAT_WS()
这样的函数来简化此操作。
答案 1 :(得分:0)
您可以使用COALESCE
和STUFF
来实现它,并避免出现空白值''
的问题,您可以在后面添加NULLIF
select stuff( coalesce(nullif('-' + col1, '-'), '') +
coalesce(nullif('-' + col2, '-'), '') +
coalesce(nullif('-' + col3, '-'), '') +
coalesce(nullif('-' + col4, '-'), '') +
coalesce(nullif('-' + col5, '-'), '') +
coalesce(nullif('-' + col6, '-'), '') +
coalesce(nullif('-' + col7, '-'), ''),
1, 1, '')
答案 2 :(得分:0)
然后您可以使用CASE
表达式来检查值是否为null
。
<强>查询强>
select case when t.[concat_string] like '%-'
then left(t.[concat_string], len(t.[concat_string]) - 1)
else t.[concat_string] end as [concat_string] from(
select
case when [col1] is null or ltrim(rtrim([col1])) = ''
then '' else [col1] + '-' end +
case when [col2] is null or ltrim(rtrim([col2])) = ''
then '' else [col2] + '-' end +
case when [col3] is null or ltrim(rtrim([col3])) = ''
then '' else [col3] + '-' end +
case when [col4] is null or ltrim(rtrim([col4])) = ''
then '' else [col4] + '-' end +
case when [col5] is null or ltrim(rtrim([col5])) = ''
then '' else [col5] + '-' end +
case when [col6] is null or ltrim(rtrim([col6])) = ''
then '' else [col6] + '-' end +
case when [col7] is null or ltrim(rtrim([col7])) = ''
then '' else [col7] end as [concat_string]
from [your_table_name]
)t;
如果任何列不是VARCHAR
,那么您可能需要CAST
到VARCHAR
答案 3 :(得分:0)
假设您已经构建了类似下面的查询。
select
isnull(col1,'') + '-' + isnull(col2,'') + '-' + isnull(col3,'') as [columns]
from yourtable
用空格替换空值。例如,尝试以下查询
select replace(replace ([columns],'|-',''), (case when
charindex ('-|',replace ([columns],'|-','')) > 0 then '-|' else '|' end),'')
from(select
isnull(col1,'|') + '-' + isnull(col2,'|') + '-' +isnull(col3,'|')[columns]
from yourtable)temp
答案 4 :(得分:0)
DECLARE @String table (String nvarchar(max))
INSERT INTO @String
SELECT '--Account--stands---'
;WITH Cte
AS
(
SELECT String From
(
SELECT Split.a.value('.', 'VARCHAR(100)') AS String,
PATINDEX('%[a-zA-Z]%',Split.a.value('.', 'VARCHAR(100)')) AS ISChar FROM
(
SELECT
CAST( '<S>' + REPLACE(STRING ,'--','</S><S>') + '</S>' AS XML) AS String from @String
) AS A
CROSS APPLY String.nodes('/S') AS Split(a)
) dt
Where dt.ISChar=1
)
SELECT DISTINCT STUFF((SELECT DISTINCT '- ' + String FROM Cte
FOr xml path ('')),1,1,'') AS String
FROM Cte
输出
String
-------
Account- stands