简体   繁体   中英

How can I update all empty string fields in a table to be null?

I have a table with 15 columns ( 10 of them are string value) and about 50000 rows.
It contain a lot empty string value ... I search if is there a query that I can pass a table name for it to iterate all values and if it equal empty then update it to NULL ..

UPDATE mytable
   SET col1 = NULLIF(col1, ''),
       col2 = NULLIF(col2, ''),
       ...

this is a simple way to do it based on table. just pass the proc the table names. you can also make a sister proc to loop thought table names and call this proc inside the while loop to work on each table in your loop logic.

CREATE PROC setNullFields 
(@TableName NVARCHAR(100))        
AS    

CREATE TABLE #FieldNames    
(    
pk INT IDENTITY(1, 1) ,    
Field NVARCHAR(1000) NULL    
);    

INSERT INTO #FieldNames    
SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName 

DECLARE @maxPK INT;    
SELECT @maxPK = MAX(PK) FROM #FieldNames    

DECLARE @pk INT;    
SET @pk = 1    

DECLARE @dynSQL NVARCHAR(1000) 

WHILE @pk <= @maxPK    
BEGIN    

 DECLARE @CurrFieldName NVARCHAR(100);    
 SET @CurrFieldName = (SELECT Field FROM #FieldNames WHERE PK = @pk)    

    -- update the field to null here:

    SET @dynSQL = 'UPDATE ' + @TableName + ' SET ' + @CurrFieldName + ' = NULLIF('+ @CurrFieldName+ ', '''' )' 
    EXEC (@dynSQL)

 SELECT @pk = @pk + 1    
END    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM