我需要一个SQL脚本,它将遍历数据库中所有表的所有nvarchar列,并将它们转换为UPPER()。知道如何自动执行此操作而无需手动指定要处理的列吗?
答案 0 :(得分:1)
我假设您有这个奇怪的要求,因为您的数据库具有区分大小写的排序规则或其他内容。注释中链接到您的问题的解决方案可以正常工作,但不会仅处理nvarchar
表上的user defined
列。
如果这是一次性要求,此解决方案应该有效,但不是最有效的方法:
DECLARE @updates TABLE
(
tablename sysname,
columnname sysname
)
DECLARE @SQL nvarchar(max);
INSERT INTO @updates (tablename,columnname)
SELECT OBJECT_NAME(c.OBJECT_ID) TableName, c.name ColumnName
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
JOIN sys.tables AS tb ON c.object_id = tb.object_id AND tb.type = 'U'
WHERE t.name = 'nvarchar' --you can change text to other datatypes
ORDER BY c.OBJECT_ID;
DECLARE @tablename sysname,@columnname sysname
DECLARE caseupdate CURSOR
FOR
Select tablename,columnname FROM @updates
OPEN caseupdate
FETCH NEXT FROM caseupdate INTO @tablename,@columnname
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = 'UPDATE '+@tablename+' SET '+@columnname+' =UPPER('+@columnname+')'
EXECUTE sp_executesql @SQL
SET @SQL=''
FETCH NEXT FROM caseupdate INTO @tablename,@columnname
END
CLOSE caseupdate
DEALLOCATE caseupdate