如何在sql server中获取char或varchar字段的长度?

时间:2010-10-04 11:19:24

标签: sql-server

我想为SQL Server编写一个脚本,它将表从ASCII更改为UNICODE。因为我需要将Char(n)更改为nchar(n),类似于varchar(n)更改为NVarchar(n)。但我无法找出n的价值。 任何人都可以告诉我,我怎样才能得到n的值。

提前致谢

4 个答案:

答案 0 :(得分:2)

试试这个:

SELECT
    sh.name+'.'+o.name AS ObjectName
        ,o.type_desc AS ObjectType
        ,s.name as ColumnName
        ,CASE
             WHEN t.name IN ('char','varchar') THEN t.name+'('+CASE WHEN s.max_length<0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length) END+')'
             WHEN t.name IN ('nvarchar','nchar') THEN t.name+'('+CASE WHEN s.max_length<0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length/2) END+')'
            WHEN t.name IN ('numeric') THEN t.name+'('+CONVERT(varchar(10),s.precision)+','+CONVERT(varchar(10),s.scale)+')'
             ELSE t.name
         END AS DataType
        ,CASE
             WHEN s.is_nullable=1 THEN 'NULL'
            ELSE 'NOT NULL'
        END AS Nullable
        ,CASE
             WHEN ic.column_id IS NULL THEN ''
             ELSE ' identity('+ISNULL(CONVERT(varchar(10),ic.seed_value),'')+','+ISNULL(CONVERT(varchar(10),ic.increment_value),'')+')='+ISNULL(CONVERT(varchar(10),ic.last_value),'null')
         END
        +CASE
             WHEN sc.column_id IS NULL THEN ''
             ELSE ' computed('+ISNULL(sc.definition,'')+')'
         END
        +CASE
             WHEN cc.object_id IS NULL THEN ''
             ELSE ' check('+ISNULL(cc.definition,'')+')'
         END
            AS MiscInfo
    FROM sys.columns                           s
        INNER JOIN sys.types                   t ON s.system_type_id=t.system_type_id and t.is_user_defined=0
        INNER JOIN sys.objects                 o ON s.object_id=o.object_id
        INNER JOIN sys.schemas                sh on o.schema_id=sh.schema_id
        LEFT OUTER JOIN sys.identity_columns  ic ON s.object_id=ic.object_id AND s.column_id=ic.column_id
        LEFT OUTER JOIN sys.computed_columns  sc ON s.object_id=sc.object_id AND s.column_id=sc.column_id
        LEFT OUTER JOIN sys.check_constraints cc ON s.object_id=cc.parent_object_id AND s.column_id=cc.parent_column_id
    WHERE o.name='YourTableName'
    order by 1,s.column_id

答案 1 :(得分:1)

从未使用它,但通过快速搜索:

sp_columns <table_name>

答案 2 :(得分:1)

查看INFORMATION_SCHEMA中的所有好东西。很多观点,有些甚至包含你要求的东西;)

答案 3 :(得分:0)

--For the value of 'n' use:

Select 
    Character_Maximum_Length AS [Size] 
FROM 
    INFORMATION_SCHEMA.Columns
WHERE 
    TABLE_NAME = 'yourTable' 
    AND COLUMN_NAME = 'yourColumn'