为动态表搜索PostgreSQL创建CURSOR

时间:2018-03-13 18:35:35

标签: sql postgresql plpgsql dynamic-sql

SQL server(MSSQL)CURSOR动态表搜索:

 DECLARE @tbl    sysname,
            @sql    nvarchar(4000),
            @params nvarchar(4000),
            @count  int

DECLARE tblcur CURSOR STATIC LOCAL FOR
   SELECT * FROM INFORMATION_SCHEMA.TABLES where TABLE_NAME like 'abc%'
OPEN tblcur

WHILE 1 = 1
BEGIN
   FETCH tblcur INTO @tbl
   IF @@fetch_status <> 0
      BREAK

   SELECT @sql =
   N' SELECT @cnt = COUNT(*) FROM dbo.' + quotename(@tbl) '
   EXEC sp_executesql @sql, @cnt = @count OUTPUT

   PRINT @tbl + ': ' + convert(varchar(10), @count) + ' modified rows.'
END

DEALLOCATE tblcur

我想要这个用于PostgreSQL。

我做了什么:

 DO $$
DECLARE
    i varchar;
    searchsql text;
    temp int;
BEGIN
FOR i IN select table_schema from information_schema.columns where table_schema like 'abc%' 
LOOP
searchsql := 'select count(*) from' || quote_ident(i) ;

    EXECUTE searchsql;
    --IF (temp > 0) THEN
    --  RAISE NOTICE  'Schema % % and count' ,i , temp;
    --END IF;
    RAISE NOTICE  'Schema %' ,i ;
    RAISE NOTICE  'Script %' ,searchsql ;
END LOOP;
END
$$ LANGUAGE plpgsql;

我是新的PostgreSQL。

1.如何像sql server(MSSQL)一样计算?

2.有更好的方法吗?

先谢谢。

0 个答案:

没有答案