计算SQL表中的字符总数

时间:2019-01-08 21:13:42

标签: sql sql-server

我想计算表格中的字符总数。

我知道如何在一列中做到这一点:

select sum(leng)
from (
    select len(column) as leng
    from table
) as Total

但是如何对表中的每一列执行此操作?

我想到的一种方法是

select sum(len(col1) + len(col2) + len(3) + ...) as TotalChracters
from Table

但是我需要对500多个表执行此操作,并且每个表都有很多列。我希望有一种适用于一个表的通用代码,只需更改每个循环的表名就可以轻松地在Python中循环。

1 个答案:

答案 0 :(得分:1)

我有一些不运行查询的代码,但它几乎与数据库中任意数量的表和列所需的代码相同。 另外,包括ISNULL,因此,如果表为空,则将显示0:

WITH CTE AS (
SELECT T.Name as Table_Name, 
    C.Name as Column_Name,
    ROW_NUMBER() OVER (PARTITION BY T.Name ORDER BY T.Name, C.Name) AS RowASC,
    ROW_NUMBER() OVER (PARTITION BY T.Name ORDER BY T.Name, C.Name DESC) AS RowDESC
FROM sysobjects T 
INNER JOIN syscolumns C
  ON T.ID = C.ID
WHERE T.XType = 'U'
)
SELECT *, 
    CASE WHEN RowASC = 1 THEN 'SELECT ISNULL(SUM(' ELSE '' END +
    CASE WHEN RowASC = 1 THEN 'LEN('+Column_Name+')' ELSE '+LEN('+Column_Name+')' END +
    CASE WHEN RowDESC = 1 THEN '), 0) AS [TotalCharacters on Table: '+Table_Name+']
    FROM '+Table_Name +' UNION ' ELSE '' END AS Query
FROM CTE
ORDER BY Table_Name, Column_Name;

只需复制右侧的列(查询)并粘贴到新的查询窗口中即可。