Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Convert NULL to string.empty

Tags:

sql

I'm trying to perform some upgrade maintenance on our database. I need to move 3 columns of data from all rows of one table and insert that data as new rows in a new table.

INSERT INTO [dbo].[SnmpSettings]([NetworkDiscoveryId], [RoCommunities], [RwCommunities])
    SELECT id, Ro_Community, RW_Communities
    FROM [dbo].[Network_Discovery] 

The above code would work fine, but Ro_Community and RW_Communities allow NULL where as RoCommunities and RwCommunities do not allow NULL. How should I convert NULLs to the empty string and then insert into my new table?

EDIT:

INSERT INTO [dbo].[SnmpSettings]([NetworkDiscoveryId], [RoCommunities], [RwCommunities])
    SELECT id, Ro_Community, RW_Communities
    ISNULL(Ro_Community,'')
    FROM [dbo].[Network_Discovery] 


Msg 102, Level 15, State 1, Line 27
Incorrect syntax near 'Ro_Community'.
like image 771
Sean Anderson Avatar asked Aug 29 '26 05:08

Sean Anderson


1 Answers

SELECT ISNULL(Ro_Community, '')

or

SELECT COALESCE(Ro_Community, '')

Note: COALESCE is supported since SQL Server 2005. It is part of the ANSI-92 SQL standard, so many suggest it's preferred over ISNULL. However there are also reports that it is a bit slower.

like image 52
bfavaretto Avatar answered Aug 30 '26 19:08

bfavaretto