从 SQL 中的不同表访问两个不同字段时如何添加分隔符
How to add a separator when accessing two different fields from different tables in SQL
DECLARE @test1 varchar = 'This is test 1';
DECLARE @test2 varchar = 'This is test 2';
SELECT
'Expected output' = isnull(@test1, '') + '. ' + isnull(@test2, '')
预期输出应为“这是测试 1。这是测试 2”。但是,如果 @test1
中没有任何内容,则不显示“.”分隔符。
希望有人能帮帮我。
如果您使用的是最新版本的 SQL 服务器,只需使用 CONCAT_WS
:
DECLARE @test1 varchar(30) = 'This is test 1'; --Always define your length, precision and scale!
DECLARE @test2 varchar(30) = 'This is test 2'; --Always define your length, precision and scale!
/*
{'Literal String Alias' = Expression} is deprecated! Don't use it.
Don't, however, use literal strings for aliases at all, it is confusing.
Ideally, don't use object names/aliases that require delimit identification.
If you must use the T-SQL ([]) or ANSI (") delimit identifiers.
*/
SELECT CONCAT_WS('.',@test1, @test2) AS ExpectedResult;
如果您使用的是旧版本的 SQL 服务器,请在每个值的开头添加分隔符前缀,并使用 STUFF
删除第一个:
DECLARE @test1 varchar(30) = 'This is test 1'; --Always define your length, precision and scale!
DECLARE @test2 varchar(30) = 'This is test 2'; --Always define your length, precision and scale!
SELECT STUFF(CONCAT('.' + @test1,'.' + @test2),1,1,'') AS ExpectedResult;
if there is nothing in @test1 then do not show the ". " separator.
也许最简单的方法是:
SELECT CONCAT(@test1 + '. ', @test2)
CONCAT()
忽略 NULL
值,但 +
不会。所以如果 @test1
是 NULL
那么第一个表达式是 NULL
并且被忽略。
DECLARE @test1 varchar = 'This is test 1';
DECLARE @test2 varchar = 'This is test 2';
SELECT
'Expected output' = isnull(@test1, '') + '. ' + isnull(@test2, '')
预期输出应为“这是测试 1。这是测试 2”。但是,如果 @test1
中没有任何内容,则不显示“.”分隔符。
希望有人能帮帮我。
如果您使用的是最新版本的 SQL 服务器,只需使用 CONCAT_WS
:
DECLARE @test1 varchar(30) = 'This is test 1'; --Always define your length, precision and scale!
DECLARE @test2 varchar(30) = 'This is test 2'; --Always define your length, precision and scale!
/*
{'Literal String Alias' = Expression} is deprecated! Don't use it.
Don't, however, use literal strings for aliases at all, it is confusing.
Ideally, don't use object names/aliases that require delimit identification.
If you must use the T-SQL ([]) or ANSI (") delimit identifiers.
*/
SELECT CONCAT_WS('.',@test1, @test2) AS ExpectedResult;
如果您使用的是旧版本的 SQL 服务器,请在每个值的开头添加分隔符前缀,并使用 STUFF
删除第一个:
DECLARE @test1 varchar(30) = 'This is test 1'; --Always define your length, precision and scale!
DECLARE @test2 varchar(30) = 'This is test 2'; --Always define your length, precision and scale!
SELECT STUFF(CONCAT('.' + @test1,'.' + @test2),1,1,'') AS ExpectedResult;
if there is nothing in @test1 then do not show the ". " separator.
也许最简单的方法是:
SELECT CONCAT(@test1 + '. ', @test2)
CONCAT()
忽略 NULL
值,但 +
不会。所以如果 @test1
是 NULL
那么第一个表达式是 NULL
并且被忽略。