查询表中所有字段的最大长度(大数据情况)

Posted 木龙

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了查询表中所有字段的最大长度(大数据情况)相关的知识,希望对你有一定的参考价值。

DECLARE @tableName NVARCHAR(50)= home;

IF OBJECT_ID(NTableColumnMaxLen, NU) 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;

 

以上是关于查询表中所有字段的最大长度(大数据情况)的主要内容,如果未能解决你的问题,请参考以下文章

查询表中所有字段的最大长度

Mysql varchar字段长度越大越好吗?

Solr Highlighting:如何为同一字段请求多个片段长度?

postgresql数据库中,查询一个字段允许的最大长度的SQL语句怎么写?

db2 怎么在所有表查询某个字段的信息

数据库建表的时候明明varchar还没有最大但是提示说长度太长的情况