How to concatenate two Data?

Asked

Viewed 497 times

2

How to concatenate two dates of the type DateTime, one of which may have its value equal to NULL, I’m trying this way;

DECLARE @DATA1 DATETIME = GETDATE(), @DATA2 DATETIME    
select  Convert(nvarchar(50),@DATA1 , 121) +'|'+ Convert(nvarchar(50), @DATA2, 121) 

But it returns null, when I really wanted the value of GETDATE() + something like empty or null.

  • Everything you concatenate with NULL will result in NULL, so you first need to change null to something else, and then concatenate. The @Ricardo response is correct.

2 answers

8


So I tried with ISNULL()

Here worked:

DECLARE @DATA1 DATETIME = GETDATE(), @DATA2 DATETIME    
select  Convert(nvarchar(50),@DATA1 , 121) +'|'+ isnull(Convert(nvarchar(50), @DATA2, 121),'')
  • 2

    Besides ISNULL, you can use COALESCE, which gives the same result and is a standard ANSI SQL function.

3

DECLARE @DATA1 DATETIME, @DATA2 DATETIME;
SET @DATA1 = getdate()
SET @DATA2 = null
SELECT  CASE WHEN (@DATA1 IS NULL) THEN '' ELSE Convert(nvarchar(50),@DATA1 , 121) END +'|'+ CASE WHEN (@DATA2 is null) THEN '' ELSE Convert(nvarchar(50), @DATA2, 121) END

Browser other questions tagged

You are not signed in. Login or sign up in order to post.