在获取所有表的一列中的最大记录长度方面,我遇到了麻烦。
我只想显示特定列的每个表的最大长度。
下面是我尝试过的方法,我已经找到了返回所需列的方法,但是现在,我需要获取最大len。我知道这不是正确的方法。
select max(len(site)) as site from
(
SELECT t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE 'site%')A
预期结果将显示列名称,表名称以及该列的记录的最大长度。
预先感谢
答案 0 :(得分:3)
我不明白您真正想做什么,但我想您想要类似的东西
CREATE TABLE T1(
Site1 VARCHAR(45)
);
CREATE TABLE T2(
Site2 VARCHAR(45)
);
INSERT INTO T1 VALUES ('A'), ('AA');
INSERT INTO T2 VALUES ('BBB'), ('BBBBB');
DECLARE @SQL NVARCHAR(MAX) = 'SELECT ';
SELECT @SQL = @SQL +
N'(SELECT MAX(LEN(' + --You can also add ISNULL([Col],0) to get 0
QUOTENAME(c.name) + ')) FROM '+
QUOTENAME(t.name) + ') AS ' +
QUOTENAME(t.name + '.'+c.name) + ', '
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE 'site%';
SET @SQL = LEFT(@SQL, LEN(@SQL)-1);
EXEC sp_executesql @SQL;
哪个会返回:
+----------+----------+
| T1.Site1 | T2.Site2 |
+----------+----------+
| 2 | 5 |
+----------+----------+
答案 1 :(得分:0)
尝试一下:您将获得要执行的单个脚本。
select 'select Max(len('+COLUMN_NAME+')),'''+COLUMN_NAME+ ''' as ColumnName ,'''+TABLE_NAME+''' as TableName from ' +table_name
from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME = 'YourColumnName'
答案 2 :(得分:0)
如果我理解您的问题,则可以尝试生成动态SQL语句并执行以下语句:
-- Declarations
DECLARE @stm nvarchar(max)
SET @stm = N''
-- Dynamic SQL
SELECT @stm = (
SELECT CONCAT(
N'UNION ALL ',
N'SELECT ''',
t.name,
N''' AS TableName, ''',
c.name,
N''' AS ColumnName, ',
N'ValueLength = (SELECT MAX(LEN(',
QUOTENAME(c.name),
')) FROM ',
QUOTENAME(t.name),
N')'
)
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE 'site%'
ORDER BY t.name, c.name
FOR XML PATH('')
)
SET @stm = STUFF(@stm, 1, 10, N'')
-- Execution
PRINT @stm
EXEC sp_executesql @stm