USE [AdventureWorks2012]
GO
--Create test table with two columns to hold string & default NULL
CREATE
TABLE
Test_Null(Id
INT
IDENTITY(1,1),StringNull
VARCHAR
(10) ,DefaultNull
(10))
INSERT
Test_Null (StringNull)
SELECT
'NULL'
Test_Null
,
NULL
--Execute below two queries to find how "IS NULL" works with string & default NULL
*
FROM
WHERE
StringNULL
IS
DefaultNull
--Execute below two queries to find how "ISNULL" works with string & default NULL
ISNULL
(StringNULL,0) StringNULL
(DefaultNull,0) DefaultNull
SET
NOCOUNT
ON
DECLARE
@query NVARCHAR(
MAX
),
@table_count
@column_count
@tablename
(100),
@Columnname
@Schemaname
(100) =
'HumanResources'
--schema names to be passed
@i
= 1,
@j
= 1
@MyTableVar
(Number
IDENTITY(1,1),
Table_list
(200));
@MyColumnVar
Column_list
INTO
name
sys.tables
TYPE =
'U'
AND
SCHEMA_NAME(SCHEMA_ID) = @Schemaname
@table_count =
(Number)
from
WHILE @i <= @table_count
BEGIN
@tablename = Table_list
Number = @i
C.
SYS.columns C
INNER
JOIN
SYS.tables T
T.object_id = C.object_id
SYS.types TY
TY.user_type_id = C.user_type_id
TY.system_type_id = C.system_type_id
SCHEMA_NAME(T.SCHEMA_ID) = @Schemaname
OBJECT_NAME(T.OBJECT_ID) = @tablename
T.type =
C.is_nullable = 1
TY.system_type_id
IN
(167,175,231,239)
--only character columns
ORDER
BY
C.column_id
@column_count =
WHILE @j <= @column_count
@Columnname = Column_list
Number = @j
@query =
'UPDATE ['
+@Schemaname+
'].['
+@tablename+
'] SET ['
+@Columnname+
'] = NULL WHERE ['
+@Columnname +
'] = '
''
+
CHAR
(10) +
'GO'
@j = @j + 1
PRINT @query
--To execute the generated Update scripts
--EXEC (@query)
END
@i = @i + 1
@Schemaname ii) Above code will generate UPDATE scripts only for character columns(VARCHAR,CHAR,NVARCHAR) iii) Code is tested and working with SQL Server 2008 ,SQL Server 2012.
My first post - started to post on TechNet Wiki with a simple script...