zoukankan      html  css  js  c++  java
  • 查询表中所有字段的最大长度(大数据情况)

    DECLARE @tableName NVARCHAR(50)= 'home';
    
    IF OBJECT_ID(N'TableColumnMaxLen', N'U') IS  NULL
        BEGIN
            CREATE TABLE TableColumnMaxLen
                (
                  TableName NVARCHAR(50) NOT NULL ,
                  ColumnName NVARCHAR(50) NOT NULL ,
                  ColumnMaxLen INT NOT NULL ,
                  PRIMARY KEY ( TableName, ColumnName )
                );
        END;
    DECLARE @columnName NVARCHAR(50);
    DECLARE @columnMaxLen INT;
    DECLARE @sql NVARCHAR(MAX);
    DECLARE @initState INT= -1;
    DECLARE @searchingState INT= -2;
    IF NOT EXISTS ( SELECT  1
                    FROM    dbo.TableColumnMaxLen
                    WHERE   TableName = @tableName )
        BEGIN
            INSERT  TableColumnMaxLen
                    SELECT  @tableName ,
                            COLUMN_NAME ,
                            @initState
                    FROM    INFORMATION_SCHEMA.COLUMNS
                    WHERE   TABLE_NAME = @tableName;
        END;
    
    WHILE 1 = 1
        BEGIN
            SET @columnName = ( SELECT TOP 1
                                        ColumnName
                                FROM    TableColumnMaxLen
                                WHERE   TableName = @tableName
                                        AND ColumnMaxLen = @initState
                              );
            IF @columnName IS NULL
                BREAK;
    
            UPDATE  TableColumnMaxLen
            SET     ColumnMaxLen = @searchingState
            WHERE   TableName = @tableName
                    AND ColumnName = @columnName;
    
            SET @sql = 'SELECT @columnMaxLen=ISNULL(MAX(LEN([' + @columnName
                + '])), 0) FROM ' + @tableName;
          --  PRINT @sql;
            EXEC sp_executesql @sql, N'@columnMaxLen int out', @columnMaxLen OUT;
    
            UPDATE  TableColumnMaxLen
            SET     ColumnMaxLen = @columnMaxLen
            WHERE   TableName = @tableName
                    AND ColumnName = @columnName;      
        END;
    
    SELECT  *
    FROM    TableColumnMaxLen
    WHERE   TableName = @tableName;
  • 相关阅读:
    SQL进阶-索引设置&sql优化
    SQL进阶-去重
    SQL进阶-隐式类型转换
    SQL进阶-行转列&列转行
    用Spring实现文件上传(CommonsMultipartFile)!
    在Maven父项目下创建子项目
    Maven下把父项目下的子项目导出到myeclipse中
    oracle数据库的导入导出命令
    配置环境变量
    Nginx反向代理的配置
  • 原文地址:https://www.cnblogs.com/lizhanglong/p/6696722.html
Copyright © 2011-2022 走看看