我需要将特定SCHEMA的所有空值都更新为0。最简单的方法是什么,因为我有很多表/列?
样本数据:
CREATE TABLE [mySchema].[test1](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ParentID] [int] NULL,
[ClassCode] [int] NULL,
[ClassValue] [int] NULL,
CONSTRAINT [PK_test1] PRIMARY KEY CLUSTERED ([ID] ASC)
)
CREATE TABLE [mySchema].[test2](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ParentID] [int] NULL,
[ClassCode] [int] NULL,
[ClassValue] [int] NULL,
CONSTRAINT [PK_test2] PRIMARY KEY CLUSTERED ([ID] ASC)
)
INSERT INTO test1 (ParentID,ClassCode,ClassValue) VALUES (100,1,NULL)
INSERT INTO test1 (ParentID,ClassCode,ClassValue) VALUES (100,NULL,NULL)
INSERT INTO test1 (ParentID,ClassCode,ClassValue) VALUES (100,1,2)
INSERT INTO test1 (ParentID,ClassCode,ClassValue) VALUES (100,NULL,2)
INSERT INTO test2 (ParentID,ClassCode,ClassValue) VALUES (100,1,NULL)
INSERT INTO test2 (ParentID,ClassCode,ClassValue) VALUES (100,NULL,NULL)
INSERT INTO test2 (ParentID,ClassCode,ClassValue) VALUES (100,1,2)
INSERT INTO test2 (ParentID,ClassCode,ClassValue) VALUES (100,NULL,2)
结果应为:
Test1
+----+----------+-----------+------------+
| ID | ParentID | ClassCode | ClassValue |
+----+----------+-----------+------------+
| 1 | 100 | 1 | 0 |
| 2 | 100 | 0 | 0 |
| 3 | 100 | 1 | 2 |
| 4 | 100 | 0 | 2 |
+----+----------+-----------+------------+
测试2
+----+----------+-----------+------------+
| ID | ParentID | ClassCode | ClassValue |
+----+----------+-----------+------------+
| 1 | 100 | 1 | 0 |
| 2 | 100 | 0 | 0 |
| 3 | 100 | 1 | 2 |
| 4 | 100 | 0 | 2 |
+----+----------+-----------+------------+
谢谢。
答案 0 :(得分:2)
下面的脚本将生成一条update语句,以将所有空值更新为0。
SELECT 'UPDATE ' + TABLE_NAME + ' SET [' + COLUMN_NAME + '] = 0 WHERE [' +
COLUMN_NAME + '] IS NULL'
FROM INFORMATION_SCHEMA.COLUMNS
-- WHERE TABLE_NAME = 'YOURTABLENAME'
取消注释最后一行以为特定表生成脚本。
答案 1 :(得分:2)
您可以通过SQL Server元数据表(information_schema.columns
)过滤动态创建语句:
your_specific_schema
)这是示例代码:
declare @sql nvarchar(max) =''
select @sql = @sql + 'update [' + table_schema + '].[' + table_name + ']'
+ ' set [' + column_name + '] = 0 where [' + column_name + '] is null'
+ char(10)
from information_schema.columns
where data_type in ('int','bigint') --ad all numeric types you want to set to 0
and TABLE_SCHEMA = 'your_specific_schema'
print @sql
输出应如下所示:
一旦检查了生成的脚本,就可以执行它:
,或者您可以直接从变量@sql
执行该语句,并将该语句附加到上面的查询中:
exec (@sql)