查找具有指定列名的所有表,并将值设置为NULL

时间:2015-01-08 15:33:18

标签: sql sql-server tsql sql-server-2012

我知道如何在数据库中查找具有指定列名的所有表:

SELECT  TABLE_NAME
        , COLUMN_NAME
FROM    INFORMATION_SCHEMA.COLUMNS
WHERE   COLUMN_NAME LIKE '%Name%'

因此,我得到了一张包含TABLE_NAMECOLUMN_NAME的表格。是否可以将查询接收的列中的所有值设置为NULL?

3 个答案:

答案 0 :(得分:0)

sp_MSforeachtable没有被广泛使用。它遍历每个表并执行指定的语句。 [?]是表名的替身。请在尝试之前备份您的数据库。

EXEC sp_MSforeachtable 'UPDATE [?] SET SomeColumn = NULL'

答案 1 :(得分:0)

使用Dynamic Sql。试试这个。

DECLARE @sql NVARCHAR(max)=''

SELECT @sql += 'update ' + TABLE_NAME + ' set ' + COLUMN_NAME + '= NULL '
FROM   INFORMATION_SCHEMA.COLUMNS
WHERE  COLUMN_NAME LIKE '%Name%'

--print @sql
EXEC Sp_executesql @sql 

答案 2 :(得分:0)

您无法在查询中定义每个表和每列。为此,您需要动态选择表和列并执行它。你可以动态地使用光标

DECLARE @TableName VARCHAR(100)=''
DECLARE @ColumnName VARCHAR(100)
DECLARE @PreviousTableName VARCHAR(100)='' 
DECLARE @PreviousColumnName NVARCHAR(MAX)=''
DECLARE @ROWNO INT
DECLARE @MAXCOUNT INT

DECLARE @UPDATESQL NVARCHAR(MAX)
DECLARE @COLSSQL NVARCHAR(MAX)


-- Here you declare which all columns you need to loop in Cursor
DECLARE CUR CURSOR FOR 
SELECT  TABLE_NAME, COLUMN_NAME
-- Find Row number for each table
,ROW_NUMBER() OVER(PARTITION BY TABLE_NAME ORDER BY COLUMN_NAME) RNO,
-- Gets the count of columns in each table
COUNT(COLUMN_NAME) OVER(PARTITION BY TABLE_NAME) CNT     
FROM    INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '%TE%'
ORDER BY TABLE_NAME, COLUMN_NAME 

OPEN CUR


FETCH NEXT FROM CUR 
INTO @TableName,@ColumnName,@ROWNO,@MAXCOUNT

WHILE @@FETCH_STATUS = 0
BEGIN

    SET @PreviousColumnName = @PreviousColumnName + @ColumnName + '=NULL,'

    -- If current row is last record of the table in the loop
    IF(@ROWNO = @MAXCOUNT)
    BEGIN
        SET @UPDATESQL = 'UPDATE '+@TableName+' SET ' + @PreviousColumnName
        SET @UPDATESQL = LEFT(@UPDATESQL, LEN(@UPDATESQL) - 1)
        EXEC SP_EXECUTESQL @UPDATESQL
        SET @PreviousColumnName = ''            
    END

    -- Fetches next record and increments the loop
    FETCH NEXT FROM CUR 
    INTO @TableName,@ColumnName,@ROWNO,@MAXCOUNT
END 

CLOSE CUR;
DEALLOCATE CUR;