gpt4 book ai didi

sql - 列出具有最大长度和最大长度的所有 SQL 列

转载 作者:行者123 更新时间:2023-12-04 00:19:33 24 4
gpt4 key购买 nike

我试图从表中获取所有列的列表,包括它们的数据类型、数据长度和该列中最长值的长度。

我有这个 SQL 来获取列及其数据类型和长度:

SELECT 
Object_Name(c.object_id),
c.name 'Column Name',
t.Name 'Data type',
c.max_length 'Max Length'
FROM
sys.columns c
INNER JOIN
sys.types t ON c.system_type_id = t.system_type_id
WHERE
c.object_id = OBJECT_ID('MyTable')

我有这个 SQL 来获取一个值的最大长度:
SELECT Max(Len(MyColumn))
FROM MyTable

但我无法弄清楚如何将它们结合起来。我正在使用 SQL Server 2008。

最佳答案

感谢您的建议。我想出了以下解决方案。它为我提供了我需要的数据,但有兴趣看看它是否可以提高效率。

declare @results table
(
ID varchar(36),
TableName varchar(250),
ColumnName varchar(250),
DataType varchar(250),
MaxLength varchar(250),
Longest varchar(250),
SQLText varchar(250)
)

INSERT INTO @results(ID,TableName,ColumnName,DataType,MaxLength,Longest,SQLText)
SELECT
NEWID(),
Object_Name(c.object_id),
c.name,
t.Name,
case
when t.Name != 'varchar' Then 'NA'
when c.max_length = -1 then 'Max'
else CAST(c.max_length as varchar)
end,
'NA',
'SELECT Max(Len(' + c.name + ')) FROM ' + OBJECT_SCHEMA_NAME(c.object_id) + '.' + Object_Name(c.object_id)
FROM
sys.columns c
INNER JOIN
sys.types t ON c.system_type_id = t.system_type_id
WHERE
c.object_id = OBJECT_ID('MyTable')


DECLARE @id varchar(36)
DECLARE @sql varchar(200)
declare @receiver table(theCount int)

DECLARE length_cursor CURSOR
FOR SELECT ID, SQLText FROM @results WHERE MaxLength != 'NA'
OPEN length_cursor
FETCH NEXT FROM length_cursor
INTO @id, @sql
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO @receiver (theCount)
exec(@sql)

UPDATE @results
SET Longest = (SELECT theCount FROM @receiver)
WHERE ID = @id

DELETE FROM @receiver

FETCH NEXT FROM length_cursor
INTO @id, @sql
END
CLOSE length_cursor
DEALLOCATE length_cursor


SELECT
TableName,
ColumnName,
DataType,
MaxLength,
Longest
FROM
@results

关于sql - 列出具有最大长度和最大长度的所有 SQL 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14482897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com