I am looking for a script which finds and replaces all fields of type string within a DB with specified text.
The script would for example take the following parameters:
- Search for:
null - Replace with:
empty-string
The primary string data types in SQL Server: Varchar, NVarchar, Text.
This script would then comb through all string based table data and look for in this case null and replace it with a empty string.
Ok I've put together the following code in the meantime.
-- Specify 'dbo' for all tables
DECLARE @schemaName VARCHAR(5) = 'dbo'
BEGIN
DECLARE @tableName VARCHAR(255) -- table name
DECLARE @tableID INT -- table id (aka syst.table.object_id)
DECLARE table_cursor CURSOR FOR
SELECT T.object_id AS TableID, T.name AS TableName FROM sys.tables T
INNER JOIN sys.schemas S ON S.schema_id = T.schema_id
WHERE S.name = @schemaName
OPEN table_cursor
FETCH NEXT FROM table_cursor INTO @tableID, @tableName
WHILE @@FETCH_STATUS = 0
BEGIN
-- construct each tables queries
DECLARE @totalColumnsFound INT = (SELECT COUNT(*) FROM sys.columns C WHERE OBJECT_ID = @tableID
-- text and nvarchar column data types chosen for me (if you need more like ntext, varcahr see sys.types for their ids)
AND (C.system_type_id = 35 OR c.system_type_id = 231))
IF (@totalColumnsFound > 0)
BEGIN
DECLARE @tableUpdateQuery VARCHAR(MAX) = 'update ' + @schemaName + '.' + @tableName + ' set ';
DECLARE @columnName VARCHAR(255) -- column name
DECLARE column_cursor CURSOR FOR
SELECT C.name AS ColumnName FROM sys.columns C WHERE OBJECT_ID = @tableID
-- text and nvarchar column data types chosen for me (if you need more like ntext, varcahr see sys.types for their ids)
AND (C.system_type_id = 35 OR c.system_type_id = 231)
OPEN column_cursor
FETCH NEXT FROM column_cursor INTO @columnName
WHILE @@FETCH_STATUS = 0
BEGIN
-- construct the columns for the update query, piece by piece.
-- This is also where you can apply your logic for how to handle the string update.
-- I am trimming string and updating nulls to empty strings here.
SET @tableUpdateQuery = @tableUpdateQuery + ' ' + @columnName + ' = ltrim(rtrim(isnull(' + @columnName + ',''''))),'
FETCH NEXT FROM column_cursor INTO @columnName
END
CLOSE column_cursor
DEALLOCATE column_cursor
-- trim last comma from string
SET @tableUpdateQuery = LEFT(@tableUpdateQuery, LEN(@tableUpdateQuery) - 1)
/** debuging purposes **
print 'Updating table --> ' + @tableName
print @tableUpdateQuery
print ' '
*/
-- execute dynamic sql
EXEC(@tableUpdateQuery)
END
FETCH NEXT FROM table_cursor INTO @tableID, @tableName
END
CLOSE table_cursor
DEALLOCATE table_cursor
END
--GO
select 'UPDATE ' + quotename(TABLE_NAME) + ' SET ' + quotename(COLUMN_NAME) + ' = '''' WHERE ' + quotename(COLUMN_NAME) + ' IS NULL;' from INFORMATION_SCHEMA.COLUMNS where IS_NULLABLE = 'YES' and DATA_TYPE in ('char','nchar','varchar','nvarchar'). Just save and rerun the output.