SQL - 需要有关表更新的帮助

时间:2014-08-21 15:12:33

标签: sql sql-server-2005

我有一张表:

enter image description here

我正在尝试在所有列中使用'NULL'更新'无数据'。有更新的简单程序吗?谢谢。

1 个答案:

答案 0 :(得分:1)

对每一栏重复一次:

UPDATE table
SET Bleeding_event_1 = NULL
WHERE Bleeding_event_1 = 'No Data'

另一种方法,在代码上更复杂,但由于它是动态的,它将适应任意数量的列。你只需运行一次就能完成所有列的操作!

USE <dbname_where_table_is>
GO

DECLARE @column varchar(256)
DECLARE @sql varchar(512)

-- We'll use a cursor to cycle through each column name belonging to the table
DECLARE cursor_columns CURSOR FOR
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS WITH (NOLOCK)
WHERE TABLE_NAME = '<table_name>'  -- If you have more than one table with same name, add schema filter

OPEN cursor_columns
FETCH NEXT FROM cursor_columns INTO @column

WHILE @@FETCH_STATUS = 0
BEGIN
    -- Again, may use <schema_name>.<table_name> instead of just <table_name>
    SET @sql = 'UPDATE <table_name> SET ' + @column + ' = NULL WHERE ' + @column + ' = ''No Data'''
    EXEC(@sql)
    FETCH NEXT FROM cursor_columns INTO @column
END

CLOSE cursor_columns
DEALLOCATE cursor_columns