我有包含大量列的 SQL 表。出于某种原因,某些列有空单元格而不是 NULL 单元格。我想让所有列中的所有空单元格都为 NULL。
我知道单列的方法是:
UPDATE your_table SET column = NULL WHERE column = ''
但是,我不确定如何为所有列有效地执行类似的逻辑,而不必一一编写列名。
谢谢,
我有包含大量列的 SQL 表。出于某种原因,某些列有空单元格而不是 NULL 单元格。我想让所有列中的所有空单元格都为 NULL。
我知道单列的方法是:
UPDATE your_table SET column = NULL WHERE column = ''
但是,我不确定如何为所有列有效地执行类似的逻辑,而不必一一编写列名。
谢谢,
Run the following query:
SELECT 'UPDATE yourtable SET ' + name + ' = NULL WHERE ' + name + ' = '''';'
FROM syscolumns
WHERE id = object_id('yourtable')
AND isnullable = 1;
The output of this query will be a chunk of SQL script like this:
UPDATE yourtable SET column1 = NULL WHERE column1 = '';
UPDATE yourtable SET column2 = NULL WHERE column2 = '';
UPDATE yourtable SET column3 = NULL WHERE column3 = '';
-- etc...
Copy and paste that SQL script into a new query and run it to update all your columns.
您可以进行查询syscolumns
以获取列列表,并使用结果来构建您的查询。
select quotename(name) + ' = nullif (' + quotename(name)+ ','''')'
from syscolumns
where id = object_id('yourtable')
此外,如果您将查询编写为
update yourtable
set
yourcolumn=nullif(yourcolumn, ''),
yourcolumn2=nullif(yourcolumn2, ''),
...
那么您可以在没有 where 子句的单个查询中执行此操作
实际上,当我导入平面文件数据集时,我每天都会使用上面 Robert N 的答案,所以我将它放入一个存储过程中,我可以将表名传递给它。它只是用更新语句填充临时表,然后执行表中的每一行。
USE [master]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: LikeableBias
-- Create date: 2016-06-27
-- Description: Finds and NULLs all blank values in table where column allows nulls
-- =============================================
CREATE PROCEDURE [dbo].[sproc_NullBlanks]
@tablename NVARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
--------Insert update statements to temp table for execution
DECLARE @statements TABLE (statement NVARCHAR(MAX))
INSERT INTO @statements
( statement )
SELECT ('UPDATE '+@tablename+' SET [' + name + '] = NULL WHERE ' + name + ' = '''';')
FROM syscolumns
WHERE id = OBJECT_ID(@tablename)
AND isnullable = 1;
--------Open cursor, execute statements, then close cursor
DECLARE @statement NVARCHAR(MAX)
DECLARE cur CURSOR LOCAL FOR
SELECT statement FROM @statements
OPEN cur
FETCH NEXT FROM cur INTO @statement
WHILE @@FETCH_STATUS = 0 BEGIN
EXEC sys.sp_executesql @statement
FETCH NEXT FROM cur INTO @statement
END
CLOSE cur
DEALLOCATE cur
END
GO