0

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

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  

让我知道我在哪里做错了。

4

2 回答 2

5

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

update MyTable set myColumn = null;

但这不是:

update MyTable set @myColumn = null;

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

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

 exec(@sql);
于 2013-11-05T22:49:42.230 回答
0
declare @SQL nvarchar(max)
declare @Countt bigint

SELECT @SQL = STUFF(( SELECT ' ; Update ' + INFORMATION_SCHEMA.TABLES.TABLE_NAME + ' SET YourColumnName = YourValue' 

FROM INFORMATION_SCHEMA.TABLES LEFT OUTER JOIN  INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.TABLES.TABLE_NAME = INFORMATION_SCHEMA.COLUMNS.TABLE_NAME where INFORMATION_SCHEMA.TABLES.TABLE_TYPE =N'BASE TABLE' AND INFORMATION_SCHEMA.TABLES.TABLE_NAME = N'YourTableName' AND INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME =N'YourColumnName'
FOR XML PATH('')),1,2,'')

SET @SQL = @SQL

PRINT @SQL
EXECUTE (@SQL) 
于 2014-11-26T06:09:10.667 回答