我想遍历所有表列并替换值为“。”的所有列。在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
让我知道我在哪里做错了。
答案 0 :(得分: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);
答案 1 :(得分:1)
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)