根据特定字段名称获取所有MySQL表中的NULL记录数

时间:2014-05-06 18:33:45

标签: mysql sql stored-procedures

我正在使用MySQL,我们使用Deleted列进行“软”删除并保留历史记录。我正在尝试编写一个过程或SQL语句,它可以从每个表中获取计数。

我相信这应该是可能的,因为它让我想起了SQL注入攻击I've seen before。不同之处在于我希望将其用于良好的目的:)

我重写了那里显示的代码,但认为我的语法可能不适用于MySQL;我怎样才能纠正这个问题,还是应该找到更好的方法来实现这个目标?下面是从链接重新编写的(所以很确定它不遵循MySQL过程语法)。

这是我到目前为止所做的:

Set ansi_warnings off

Declare @T VARCHAR(255)

DECLARE Table_Cursor CURSOR FOR
  Select
    c.TABLE_NAME
  from INFORMATION_SCHEMA.columns c, INFORMATION_SCHEMA.tables t
  where 
    t.table_name = c.table_name
    and t.table_type = 'BASE TABLE'
    AND c.COLUMN_NAME = 'Deleted'

OPEN Table_Cursor

FETCH NEXT FROM Table_Cursor INTO @T
WHILE(@@FETCH_STATUS=0)
BEGIN
    EXEC ( 'SELECT COUNT(*) AS ' + @T + 'Count FROM ' + @T + ' WHERE Deleted IS NULL' );
    FETCH NEXT FROM Table_Cursor INTO @T
END

CLOSE Table_Cursor

DEALLOCATE Table_Cursor

1 个答案:

答案 0 :(得分:1)

我猜这有帮助。而不是

BEGIN
    EXEC ( 'SELECT COUNT(*) AS ' + @T + 'Count FROM ' + @T + ' WHERE Deleted IS NULL' );

    # would you not store that result somewhere?
    FETCH NEXT FROM Table_Cursor INTO @T
END

试试

BEGIN

    EXEC ( 'SELECT "@T" as tabname, COUNT(*) AS del_Count FROM ' + @T + ' WHERE Deleted IS NULL' );
    # somewhere store the number and the tabname
    FETCH NEXT FROM Table_Cursor INTO @T
END