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 ..开发者_C百科. 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
精彩评论