如何在数据库中执行查询foreach单元格

时间:2011-12-01 23:06:16

标签: sql sql-server sql-server-2008-r2

我需要在数据库的每个单元格中用NULL替换空格。 SQL server 2008 r2。我正在寻找有效的东西,但看起来像光标只是方式?

3 个答案:

答案 0 :(得分:2)

首先使用INFORMATION_SCHEMA查找所有可以为Nullable且类型为CHARVARCHAR的表和列:

SELECT TABLE_NAME, COLUMN_NAME 
FROM  MyDatabase.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'dbo'
  AND IS_NULLABLE = 'YES'

答案 1 :(得分:1)

游标永远不是答案:)

ypercube做了很难的事。您需要获取该信息并迭代它,为每个表中的每个列执行更新语句。您可以使用WHILE语句执行此操作。这是一个未经证实的例子,说明如何做到这一点:

--Set database to use
USE [MyDatabase];
GO

--Create table variable to hold table/column pairs
DECLARE @table TABLE (
    [Key] BIGINT PRIMARY KEY IDENTITY (1, 1),
    [TABLE_NAME] VARCHAR(100),
    [COLUMN_NAME] VARCHAR(100)
);

--Populate table variable
INSERT INTO @table ([TABLE_NAME], [COLUMN_NAME])
SELECT [TABLE_NAME], [COLUMN_NAME]  
FROM  MyDatabase.INFORMATION_SCHEMA.COLUMNS 
WHERE [TABLE_SCHEMA] = 'dbo' 
AND [IS_NULLABLE] = 'YES';

--Initialize counting variables
DECLARE @counter BIGINT = 1;
DECLARE @max BIGINT = (SELECT COUNT(1) FROM @table);

--Iterate through each pair
WHILE @counter <= @max
BEGIN
    --Assign the current pair values to variables
    DECLARE @TableName VARCHAR(100), @ColumnName VARCHAR(100);
    SELECT @TableName = [TABLE_NAME], @ColumnName = [COLUMN_NAME]
    FROM @table
    WHERE [Key] = @counter;

    --Execute dynamic SQL
    EXEC
    (
        'UPDATE [' + @TableName + ']' +
        'SET [' + @ColumnName + '] = NULL' +
        'WHERE RTRIM([' + @ColumnName + ']) = '''';'
    );

    --Increment the counter
    SET @counter = @counter + 1;
END

答案 2 :(得分:0)

我想这取决于你如何定义空格。以下是否有效?

update mytable set mycolumn = null where len(rtrim(ltrim(mycolumn))) = 0