此代码提供了将数据长度求和在单个列中的可能性:
select sum(datalength(column_1))
from my_table
这部分为我提供了有关my_table中列的信息
SELECT COLUMN_NAME,TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'my_table' AND TABLE_SCHEMA='my_schema'
现在我想在第二个选择结果中添加一列,每列的数据长度总和,所以我想像这样的一列:
sum(datalength(col_1))
sum(datalength(col_2))
.
.
.
sum(datalength(col_n))
您能帮我准备适当的选择以达到解释的结果吗?
编辑:我需要计算每列(所有行)中的元素有多少兆字节:
1)如果它的int type列很容易: (整数大小*行数)
2)当column为varchar时,我想在此列中添加每个varchar的大小
答案 0 :(得分:2)
如果我对您的理解正确,并且想要“ ... ...在第二个选择结果(SELECT ... FROM INFORMATION_SCHEMA.COLUMNS ...
)中添加一列,其中每一列的数据长度总和...” ,可以使用动态语句:
DECLARE @stm nvarchar(max) = N''
SELECT @stm = CONCAT(
@stm,
N'UNION ALL ',
N'SELECT ''',
COLUMN_NAME,
N''' AS [COLUMN_NAME], ''',
TABLE_SCHEMA,
N''' AS [TABLE_SCHEMA], ''',
TABLE_NAME,
N''' AS [TABLE_NAME], ',
CONVERT(nvarchar(max), ORDINAL_POSITION),
N' AS [ORDINAL_POSITION], ''',
DATA_TYPE,
N''' AS [DATA_TYPE], ',
N'(SELECT SUM(DATALENGTH(',
COLUMN_NAME,
N')) FROM ',
QUOTENAME(TABLE_SCHEMA),
N'.',
QUOTENAME(TABLE_NAME),
N') AS [DATA_LENGTH] '
)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTable' AND TABLE_SCHEMA = 'YourSchema'
SELECT @stm = STUFF(@stm, 1, 10, N'')
PRINT @stm
EXEC sp_executesql @stm
答案 1 :(得分:1)
这是这个吗?
DECLARE @SQL nvarchar(MAX),
@CRLF nchar(2) = NCHAR(13) + NCHAR(10);
DECLARE @Schema sysname = N'dbo', --Replace with appropriate Schema
@Table sysname = N'PerformanceTest'; --Replace with appropriate Table
SET @SQL = N'SELECT ' +
STUFF((SELECT N' +' + @CRLF +
N' ISNULL(SUM(DATALENGTH(' + QUOTENAME(COLUMN_NAME) + N')),0)'
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.TABLE_SCHEMA = @Schema
AND C.TABLE_NAME = @Table
FOR XML PATH(N''),TYPE).value('.','nvarchar(MAX)'),1,11,N'') +N' AS DataLengthTotal' + @CRLF +
N'FROM ' + QUOTENAME(@Schema) + N'.' + QUOTENAME(@Table) + N';';
PRINT @SQL;
EXEC sp_executesql @SQL;
似乎授予总数后OP不是 ,而是按列总计。可以通过更改以下内容轻松更改
SELECT N' +' + @CRLF +
N' ISNULL(SUM(DATALENGTH(' + QUOTENAME(COLUMN_NAME) + N')),0)'
到下面:
SELECT N', ' + @CRLF +
N' ISNULL(SUM(DATALENGTH(' + QUOTENAME(COLUMN_NAME) + N')),0) AS ' + QUOTENAME(CONCAT(C.COLUMN_NAME,N'DataLength'))
并在STUFF
表达式后删除别名。