如何为列名创建变量

时间:2013-06-03 22:01:40

标签: sql variables sql-update

我需要编写一个更新语句,将每个字段中的所有不需要的值替换为NULL。我正在使用此更新声明。

UPDATE TableName
SET    ColumnName = replace(ColumnName, 'what to replace', NULL)
WHERE  ColumnName = 'what to replace'
GO

我需要创建一个变量,它将获取INFORMATION_SCHEMA.COLUMNS数据,并一次将变量更改为每个列名,并在每列上运行UPDATE语句,将不需要的字符替换为NULL

1 个答案:

答案 0 :(得分:1)

您可以使用方便的游标(假设sql server)来执行此操作:

DECLARE @Iterator varchar(55)
DECLARE @strSQL varchar(8000) -- for dynamic sql set then exec variable
DECLARE xyz CURSOR
FOR
--Select stuff to iterate over
SELECT c.name ColumnName
FROM sys.columns c INNER JOIN
     sys.tables t ON c.object_id = t.object_id INNER JOIN
     sys.schemas s ON t.schema_id = s.schema_id
WHERE t.name = 'table'   
OPEN xyz     
FETCH NEXT FROM xyz 
INTO @Iterator    
WHILE @@FETCH_STATUS = 0
BEGIN   
--Do stuff
SET @strSQL = '
            UPDATE TableName
            SET    '+@Iterator+' = NULL
            WHERE  '+@Iterator+' = ''junk''
            GO'
PRINT (@strSQL)    
    FETCH NEXT FROM xyz 
    INTO @Iterator     
END  
CLOSE xyz 
DEALLOCATE xyz 
GO

要实际执行此更新,您需要将PRINT(@strSQL)更改为EXEC(@strSQL),PRINT首先确保语句按您的意愿读取。

更新:要遍历每个表/列,这将打印出每个表的游标,但是您无法执行外部游标。

DECLARE @Iterator varchar(55)
DECLARE @strSQL varchar(8000) -- for dynamic sql set then exec variable     
DECLARE xyz CURSOR
FOR
--Select stuff to iterate over
SELECT DISTINCT t.name TableName
FROM sys.tables t INNER JOIN
     sys.schemas s ON t.schema_id = s.schema_id
OPEN xyz    
FETCH NEXT FROM xyz 
INTO @Iterator    
WHILE @@FETCH_STATUS = 0
BEGIN       
--Do stuff
SET @strSQL = 'DECLARE @Iterator varchar(55)
                DECLARE @strSQL varchar(8000) -- for dynamic sql set then exec variable
                DECLARE xyz CURSOR
                FOR
                --Select stuff to iterate over
                SELECT c.name ColumnName
                FROM sys.columns c INNER JOIN
                     sys.tables t ON c.object_id = t.object_id INNER JOIN
                     sys.schemas s ON t.schema_id = s.schema_id
                WHERE t.name = '''+@Iterator+'''   
                OPEN xyz     
                FETCH NEXT FROM xyz 
                INTO @Iterator    
                WHILE @@FETCH_STATUS = 0
                BEGIN   
                --Do stuff
                SET @strSQL = ''
                            UPDATE '+@Iterator+'
                            SET    ''+@Iterator+'' = NULL
                            WHERE  ''+@Iterator+'' = ''''junk''''
                            GO''
                PRINT (@strSQL)    
                    FETCH NEXT FROM xyz 
                    INTO @Iterator     
                END  
                CLOSE xyz 
                DEALLOCATE xyz 
                GO
'   
PRINT (@strSQL)   
    FETCH NEXT FROM xyz 
    INTO @Iterator     
END    
CLOSE xyz 
DEALLOCATE xyz 
GO