sql server 2008-如何在一个SQL语句中获取varchar [n]字段的大小?

假设我有一个SQL表,该表具有一个称为“备注”的varchar [1000]字段。

我想制作一条SQL语句,该语句在执行时将返回1000,或者将来可能会将varchar字段的大小更改为任何大小。

类似于SELECT size(Remarks) FROM mytable

我该怎么做呢?

Daniel Allen Langdon asked 2019-10-07T21:39:14Z
8个解决方案
97 votes
select column_name, data_type, character_maximum_length    
  from information_schema.columns  
 where table_name = 'myTable'
Neil Knight answered 2019-10-07T21:39:18Z
23 votes

特别是在SQL Server上:

SELECT DATALENGTH(Remarks) AS FIELDSIZE FROM mytable

文档

MarcE answered 2019-10-07T21:39:43Z
6 votes

对于SQL Server(2008及更高版本):

SELECT COLUMNPROPERTY(OBJECT_ID('mytable'), 'Remarks', 'PRECISION');

COLUMNPROPERTY返回列或参数(标识,列/参数,属性)的信息。 PRECISION属性返回列或参数的数据类型的长度。

COLUMNPROPERTY文档

Frank answered 2019-10-07T21:40:21Z
3 votes

这将适用于SQL SERVER ...

SELECT COL_LENGTH('Table', 'Column')
Greg Quinn answered 2019-10-07T21:40:44Z
2 votes

我一直在寻找列的TOTAL大小并点击本文,我的解决方案基于MarcE的解决方案。

SELECT sum(DATALENGTH(your_field)) AS FIELDSIZE FROM your_table
ProVega answered 2019-10-07T21:41:08Z
0 votes

其中是用于计算varchar(Nn)的最大有效长度的函数:

CREATE FUNCTION [dbo].[GetMaxVarcharColumnLength] (@TableSchema NVARCHAR(MAX), @TableName NVARCHAR(MAX), @ColumnName VARCHAR(MAX))
RETURNS INT
AS
BEGIN
    RETURN (SELECT character_maximum_length FROM information_schema.columns  
            WHERE table_schema = @TableSchema AND table_name = @TableName AND column_name = @ColumnName);
END

用法:

IF LEN(@Name) > [dbo].[GetMaxVarcharColumnLength]('person', 'FamilyStateName', 'Name') 
            RETURN [dbo].[err_Internal_StringForVarcharTooLong]();
Ihor Konovalenko answered 2019-10-07T21:41:33Z
0 votes

对于t-SQL,我对varchar列使用以下查询(显示排序规则和is_null属性):

SELECT
    s.name
    , o.name as table_name
    , c.name as column_name
    , t.name as type
    , c.max_length
    , c.collation_name
    , c.is_nullable
FROM
    sys.columns c
    INNER JOIN sys.objects o ON (o.object_id = c.object_id)
    INNER JOIN sys.schemas s ON (s.schema_id = o.schema_id)
    INNER JOIN sys.types t ON (t.user_type_id = c.user_type_id)
WHERE
    s.name = 'dbo'
    AND t.name IN ('varchar') -- , 'char', 'nvarchar', 'nchar')
ORDER BY
    o.name, c.name
Andrei Sura answered 2019-10-07T21:41:57Z
0 votes
select column_name, data_type, character_maximum_length    
from INFORMATION_SCHEMA.COLUMNS
where table_name = 'Table1'
mrbengi answered 2019-10-07T21:42:14Z
translate from https://stackoverflow.com:/questions/5705316/how-to-get-the-size-of-a-varcharn-field-in-one-sql-statement