Set empty strings ('') to NULL in the whole database

前端 未结 3 1808
名媛妹妹
名媛妹妹 2020-12-18 13:39

In my database are many text columns where values are empty strings (\'\'). The empty strings need to be set to NULL. I do not know the exact schem

3条回答
  •  暖寄归人
    2020-12-18 13:50

    i think the code below is a generalised one. and you can use it any time anywhere:

        Declare @Query varchar(1000)
        declare @AllDatabaseTables table(id int,Table_Name varchar(50))
        Insert into @AllDatabaseTables select Table_Name from information_schema.tables
    
        declare @Table_Name varchar(50)
    
        declare @i int=1
        While @i<=(Select Count(*) from @AllDatabaseTables)
        BEGIN
        Select @Table_Name=Table_Name from @AllDatabaseTables Where id=@i
    
        Declare @ColumnTable table(id int,ColumnName varchar(100))
        Insert into @ColumnTable Select COLUMN_NAME from information_schema.columns Where Table_Name=@Table_Name and DATA_TYPE='varchar' --if the datatype is varchar type
        Declare @ColumnName varchar(50)
        Declare @k int=1
        While @k<=(Select count(*) from @ColumnTable)
            BEGIN
                Select @ColumnName=ColumnName from @ColumnTable where id=@k
    
                Set @Query='Update '+@Table_Name+' Set '+@ColumnName+'=NULL where '+@ColumnName+'='''' ' 
                Exec(Query)
    
                Set @k=@k+1
            END
    
    
    
        Set @i=@i+1
    
    END
    

提交回复
热议问题