更新数据库表中的所有列

use*_*700 0 sql t-sql sql-server

我想遍历所有表列并替换值为"."的所有列.在sql server中使用null值.所以我在这里写了一些逻辑.但不知何故它不起作用.

create table #AllColumns  
  (  
  ColNo int not null primary key identity(1,1),  
  ColumnName varchar(100)  
  )  
  insert into #AllColumns  
  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='TabelName'


DECLARE @i int  
DECLARE @numrows int  
DECLARE @columnName varchar(100)  
   set @i=1  
   set @numrows= (SELECT COUNT(*) FROM #AllColumns)  
   IF @numrows > 0  
    WHILE (@i <= (SELECT MAX(ColNo) FROM #AllColumns))  
    BEGIN  
        set @columnName=(select ColumnName from #AllColumns where ColNo=@i)  
        update TabelName   
        set @columnName=null  
        where @columnName='.'  
        set @i=@i+1  
    END  
drop table #AllColumns  
Run Code Online (Sandbox Code Playgroud)

让我知道我做错了什么.

Joh*_*ibb 5

您不能在集合的左侧使用变量或在类似的地方使用变量.换句话说,这是合法的

update MyTable set myColumn = null;
Run Code Online (Sandbox Code Playgroud)

但这不是:

update MyTable set @myColumn = null;
Run Code Online (Sandbox Code Playgroud)

您可以使用动态SQL来完成此操作,这意味着将SQL构建为字符串然后执行它.就像是:

 declare @MyColumn nvarchar(max) = 'Column1';
 declare @sql = 'update MyTable set ' + @MyColumn + ' = null;'

 exec(@sql);
Run Code Online (Sandbox Code Playgroud)

  • 只需将它添加到指定为@sql的字符串中,如`declare @sql ='update MyTable set'+ @MyColumn +'= null where'+ @MyColumn +'=''.''';`记住,你是以编程方式生成sql语句然后运行它. (2认同)