diff --git a/src/pl/plpgsql/src/gram.y b/src/pl/plpgsql/src/gram.y
index 92b54dd..46e7442 100644
--- a/src/pl/plpgsql/src/gram.y
+++ b/src/pl/plpgsql/src/gram.y
@@ -509,6 +509,7 @@ decl_statement	: decl_varname decl_const decl_datatype decl_collate decl_notnull
 						char		buf[1024];
 						char		*cp1;
 						char		*cp2;
+						static unsigned int cursor_count = 0;
 
 						/* pop local namespace for cursor args */
 						plpgsql_ns_pop();
@@ -539,7 +540,13 @@ decl_statement	: decl_varname decl_const decl_datatype decl_collate decl_notnull
 								*cp2++ = *cp1;
 							*cp2++ = *cp1++;
 						}
-						strcpy(cp2, "'::pg_catalog.refcursor");
+
+						/*
+						 * Append cursor count after cursor name to remove
+						 * conflict of same named cursor in different
+						 * nested levels.
+					 	 */
+						snprintf(cp2, sizeof(buf) - strlen(buf), ":%u'::pg_catalog.refcursor", cursor_count++);
 						curname_def->query = pstrdup(buf);
 						new->default_val = curname_def;
 
diff --git a/src/test/regress/expected/plpgsql.out b/src/test/regress/expected/plpgsql.out
index bed34c8..4bdccf3 100644
--- a/src/test/regress/expected/plpgsql.out
+++ b/src/test/regress/expected/plpgsql.out
@@ -3284,15 +3284,15 @@ begin
 end;
 $$ language plpgsql;
 select forc01();
-NOTICE:  5 from c
-NOTICE:  6 from c
-NOTICE:  7 from c
-NOTICE:  9 from c
-NOTICE:  10 from c
-NOTICE:  41 from c2
-NOTICE:  42 from c2
-NOTICE:  43 from c2
-NOTICE:  after loop, c2 = c2
+NOTICE:  5 from c:5
+NOTICE:  6 from c:5
+NOTICE:  7 from c:5
+NOTICE:  9 from c:5
+NOTICE:  10 from c:5
+NOTICE:  41 from c2:6
+NOTICE:  42 from c2:6
+NOTICE:  43 from c2:6
+NOTICE:  after loop, c2 = c2:6
 NOTICE:  41 from special_name
 NOTICE:  42 from special_name
 NOTICE:  43 from special_name
