SQL Server String Concatenation with Null

后端 未结 10 685
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 13:51

I am creating a computed column across fields of which some are potentially null.

The problem is that if any of those fields is null, the entire computed column will

相关标签:
10条回答
  • 2020-11-27 14:31

    Use COALESCE. Instead of your_column use COALESCE(your_column, ''). This will return the empty string instead of NULL.

    0 讨论(0)
  • 2020-11-27 14:35

    In Sql Server:

    insert into Table_Name(PersonName,PersonEmail) values(NULL,'xyz@xyz.com')
    
    PersonName is varchar(50), NULL is not a string, because we are not passing with in single codes, so it treat as NULL.
    

    Code Behind:

    string name = (txtName.Text=="")? NULL : "'"+ txtName.Text +"'";
    string email = txtEmail.Text;
    
    insert into Table_Name(PersonName,PersonEmail) values(name,'"+email+"')
    
    0 讨论(0)
  • 2020-11-27 14:37

    From SQL Server 2012 this is all much easier with the CONCAT function.

    It treats NULL as empty string

    DECLARE @Column1 VARCHAR(50) = 'Foo',
            @Column2 VARCHAR(50) = NULL,
            @Column3 VARCHAR(50) = 'Bar';
    
    
    SELECT CONCAT(@Column1,@Column2,@Column3); /*Returns FooBar*/
    
    0 讨论(0)
  • 2020-11-27 14:39

    I just wanted to contribute this should someone be looking for help with adding separators between the strings, depending on whether a field is NULL or not.

    So in the example of creating a one line address from separate fields

    Address1, Address2, Address3, City, PostCode

    in my case, I have the following Calculated Column which seems to be working as I want it:

    case 
        when [Address1] IS NOT NULL 
        then (((          [Address1]      + 
              isnull(', '+[Address2],'')) +
              isnull(', '+[Address3],'')) +
              isnull(', '+[City]    ,'')) +
              isnull(', '+[PostCode],'')  
    end
    

    Hope that helps someone!

    0 讨论(0)
  • 2020-11-27 14:39

    ISNULL(ColumnName, '')

    0 讨论(0)
  • 2020-11-27 14:46

    This example will help you to handle various types while creating insert statements

    select 
    'insert into doc(Id, CDate, Str, Code, Price, Tag )' + 
    'values(' +
          '''' + convert(nvarchar(50), Id) + ''',' -- uniqueidentifier
        + '''' + LEFT(CONVERT(VARCHAR, CDate, 120), 10) + ''',' -- date
        + '''' + Str+ ''',' -- string
        + '''' + convert(nvarchar(50), Code)  + ''',' -- int
        + convert(nvarchar(50), Price) + ',' -- decimal
        + '''' + ISNULL(Tag, '''''') + '''' + ')'  -- nullable string
    
     from doc
     where CDate> '2019-01-01 00:00:00.000'
    
    0 讨论(0)
提交回复
热议问题