在我的SQL查询中,我试图在select子句中连接两个字符串。这是预期的结果:
col A col B Result
null null &
null '' &
null XYZ XYC
'' null &
'' '' &
'' XYZ XYC
ABC null ABC
ABC '' ABC
ABC XYZ ABC-XYC
我的挑战是这样的 - 如何让“冲刺”出现在最后一个场景中,而不是其他场景?
这是我的尝试:
DECLARE @ColA as varchar(10)
DECLARE @ColB as varchar(10)
set @ColA = null; set @ColB = null; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(@ColA, '') + COALESCE(@ColB, ''), ''), '&') as 'Actual'
set @ColA = null; set @ColB = ''; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(@ColA, '') + COALESCE(@ColB, ''), ''), '&') as 'Actual'
set @ColA = null; set @ColB = 'XYC'; select 'XYC' as 'Expected', COALESCE(NULLIF(COALESCE(@ColA, '') + COALESCE(@ColB, ''), ''), '&') as 'Actual'
set @ColA = ''; set @ColB = null; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(@ColA, '') + COALESCE(@ColB, ''), ''), '&') as 'Actual'
set @ColA = ''; set @ColB = ''; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(@ColA, '') + COALESCE(@ColB, ''), ''), '&') as 'Actual'
set @ColA = ''; set @ColB = 'XYC'; select 'XYC' as 'Expected', COALESCE(NULLIF(COALESCE(@ColA, '') + COALESCE(@ColB, ''), ''), '&') as 'Actual'
set @ColA = 'ABC';set @ColB = null; select 'ABC' as 'Expected', COALESCE(NULLIF(COALESCE(@ColA, '') + COALESCE(@ColB, ''), ''), '&') as 'Actual'
set @ColA = 'ABC';set @ColB = ''; select 'ABC' as 'Expected', COALESCE(NULLIF(COALESCE(@ColA, '') + COALESCE(@ColB, ''), ''), '&') as 'Actual'
set @ColA = 'ABC';set @ColB = 'XYC'; select 'ABC-XYC' as 'Expected', COALESCE(NULLIF(COALESCE(@ColA, '') + COALESCE(@ColB, ''), ''), '&') as 'Actual'
你认为我什么时候必须做一个大案?我有很多像这样的专栏,这会让你无法忍受阅读。
谢谢!
更新:如果我使用了一个案例,那么我的选择看起来像这样,这似乎有效,但是会很痛苦。
select
case when (@ColA is not null and @ColA <> '') and
(@ColB is not null and @ColB <> '')
then @ColA + '-' + @ColB
else COALESCE(NULLIF(COALESCE(@ColA, '') + COALESCE(@ColB, ''), ''), '&')
end
真的希望有人有一些改进的建议!
答案 0 :(得分:2)
你能使用像这样的搜索案例函数吗?
Select Case When isnull(ColA, '') + isnull(ColB, '') == '' Then '&'
When isnull(ColA, '') <> '' and isnull(ColB, '') <> '' Then ColA + '-' + ColB
Else isnull(ColA, '') + isnull(ColB, '')
From Table1
答案 1 :(得分:0)
我认为这个答案与其他答案并不完全不同,但你可以试试这个:
SELECT
CASE
WHEN NULLIF(ColA,'') <> '' AND NULLIF(ColB,'') <> ''
THEN ColA + '-' + ColB
WHEN NULLIF(ColA,'') <> '' OR NULLIF(ColB,'') <> ''
THEN COALESCE(ColA,ColB)
ELSE '&'
END