标签:
随着数据库的规模越来越大,数据库的表也有成百上千,如果需要对数据库表名及字段名做操作,单个还好,直接一条语句搞定了,但如果要对整个库的所有表和字段名做操作,那就显得有点麻烦了。因此,我们需要利用sql语句做批量表名字段名修改操作。
1、获取所有数据库名:
SELECT NAME FROM MASTER..SysDatabases
2、获取所有用户表名:
SELECT NAME FROM sysobjects WHERE TYPE = ‘U‘
3、获取所有字段名:
SELECT NAME FROM SysColumns WHERE id = OBJECT_ID(‘TableName‘)
DECLARE @tablename VARCHAR(50) DECLARE @columnname VARCHAR(50) DECLARE cur_table CURSOR FOR SELECT NAME FROM sysobjects WHERE TYPE = ‘U‘ AND NAME <> ‘sysdiagrams‘ OPEN cur_table FETCH NEXT FROM cur_table INTO @tablename WHILE @@fetch_status = 0 BEGIN ----------------------------------------- DECLARE cur_column CURSOR FOR SELECT NAME FROM syscolumns WHERE id = OBJECT_ID(@tablename) OPEN cur_column FETCH NEXT FROM cur_column INTO @columnname WHILE @@fetch_status = 0 BEGIN DECLARE @columnnamefirstchar CHAR(1), @tablenamefirstchar CHAR(1), @ch VARCHAR(50), @ch1 VARCHAR(50), @uppertablename VARCHAR(50) SET @columnnamefirstchar = SUBSTRING(@columnname, 1, 1) SET @tablenamefirstchar = SUBSTRING(@tablename, 1, 1) IF ASCII(@columnnamefirstchar) BETWEEN ASCII(‘A‘) AND ASCII(‘Z‘) BEGIN SET @ch = @tablename + ‘.‘ + @columnname SET @ch1 = LOWER(@columnnamefirstchar) + SUBSTRING(@columnname, 2, LEN(@columnname) -1) EXEC sp_rename @ch, @ch1, ‘column‘ END IF ASCII(@tablenamefirstchar) BETWEEN ASCII(‘a‘) AND ASCII(‘z‘) BEGIN SET @uppertablename = UPPER(@tablenamefirstchar) + SUBSTRING(@tablename, 2, LEN(@tablename) -1) EXEC sp_rename @tablename, @uppertablename END FETCH NEXT FROM cur_column INTO @columnname END CLOSE cur_column DEALLOCATE cur_column ----------------------------------------- FETCH NEXT FROM cur_table INTO @tablename END CLOSE cur_table DEALLOCATE cur_table
执行后整个数据库的表名都会变成首字母大写,字段名首字母都会变成小写。
标签:
原文地址:http://www.cnblogs.com/zeje/p/5244222.html