简体   繁体   English

在表中将所有列设置为“null”

[英]Set all columns to `null` in a table

Is there a quick way to change all fields in a table that are null to just empty fields. 是否有一种快速方法可以将表中的所有字段更改为空字段。 I have many columns so wondered if there was a way to do it by table rather than column by column. 我有很多列,所以想知道是否有办法按表而不是逐列进行。

I need something like 我需要类似的东西

update table 1 
set * = '' 
where * is null

but obviously this is incorrect syntax 但显然这是不正确的语法

This code will generate update statements list, you have to only run it: 此代码将生成更新语句列表,您只需运行它:

SELECT  'update '+ so.name+' set '+sc.name+'= '''' where '+sc.name+' is null '   
FROM sysobjects so
JOIN syscolumns sc ON so.id = sc.id
JOIN systypes st ON sc.xtype=st.xtype  
where so.type = 'U'
and st.name in('varchar','char')
--and so.name = 'tab' <--- if you need update only one table

Here (sql fiddle) you can see how it works. 在这里(sql小提琴)你可以看到它是如何工作的。

If you want to generate a script that will update all of the NULLable fields that contain NULLs to blanks, you can use the following code: 如果要生成将所有包含NULL的NULLable字段更新为空白的脚本,可以使用以下代码:

DECLARE @TAB VARCHAR(1000) = 'ProductVendor', 
        @COL VARCHAR(1000), 
        @SQL VARCHAR(MAX) 
DECLARE UPDATE_CURSOR CURSOR LOCAL FAST_FORWARD FOR 
  SELECT t2.NAME 
    FROM (SELECT * 
            FROM SYSOBJECTS 
           WHERE XTYPE = 'u' 
                 AND NAME = @TAB)T1 
         INNER JOIN SYSCOLUMNS t2 
                 ON T1.ID = t2.ID 
   WHERE t2.ISNULLABLE = 1 

OPEN UPDATE_CURSOR 

SET @SQL = 'UPDATE ' + @TAB + ' SET ' 

FETCH NEXT FROM UPDATE_CURSOR INTO @COL 

WHILE @@FETCH_STATUS = 0 
  BEGIN 
      SET @SQL = @SQL + @COL + ' = Isnull(' + @COL + ', ''''),' 

      FETCH NEXT FROM UPDATE_CURSOR INTO @COL 
  END 

CLOSE UPDATE_CURSOR 

DEALLOCATE UPDATE_CURSOR 

SET @SQL = LEFT(@SQL, Len(@SQL) - 1) 

EXEC (@SQL) 

All you need to do is change the table name at the beginning (the TAB variable). 您需要做的就是在开头更改表名(TAB变量)。 The script generates a single query that will update all of the columns in one run. 该脚本生成一个查询,该查询将在一次运行中更新所有列。

试试这个

 update table1 set columnnames='' where columnnames ='null'

Try something like this: 尝试这样的事情:

UPDATE TABLE1 
   SET ( COL1, COL2, COL3, COL4 ) = (SELECT COL1A, 
                                            COL2A, 
                                            COL3A, 
                                            COL4A 
                                       FROM TABLE2 
                                      WHERE COL5A = TABLE1.COL5) 
 WHERE COL5 IN (SELECT COL5A 
                  FROM TABLE2) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM