码迷,mamicode.com
首页 > 数据库 > 详细

Sql Server之数据库规范——1、自动化规范命名

时间:2016-03-05 11:36:16      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

 

一、废话:

随着数据库的规模越来越大,数据库的表也有成百上千,如果需要对数据库表名及字段名做操作,单个还好,直接一条语句搞定了,但如果要对整个库的所有表和字段名做操作,那就显得有点麻烦了。因此,我们需要利用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

执行后整个数据库的表名都会变成首字母大写,字段名首字母都会变成小写。

Sql Server之数据库规范——1、自动化规范命名

标签:

原文地址:http://www.cnblogs.com/zeje/p/5244222.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!