Вопрос

I am writing a SQL stored procedure that takes in a population name as a parameter, creates a table based on the population name, and then populates the table. It works great as long as I know how many population names I am passing to it ahead of time, but I need this to work when I don't know how many populations there are in advance.

I will be passing a comma delimited string and I need the following procedure to run for each value in that string. The stored procedure is a series of Union All statements, but I only included the first one below.

DECLARE
    ID ALIAS FOR $1;
    POPULATION FOR $2;
    SQL VARCHAR(32000);
BEGIN
SQL:='CREATE TABLE DEMO_POPULATION_' ||POPULATION|| '_TABLE AS          
SELECT ' ||ID|| ' AS ID
  , '||POPULATION||' AS POPULATION
  , 'AGE' AS CATEGORY
  , MAX((SELECT AGE_MAX FROM ID_INSTANCE A JOIN DEMO_SOURCE B ON (A.ID = B.NAME) WHERE ID = ' ||ID|| ' AND POPULATION LIKE '||POPULATION||' )) AS VAL 
UNION ALL
...

Also I am working on IBM Netezza, which I know is not used by a lot of people. So a response for general SQL would be great, it just can't be something that is specific to SQL Server.

Это было полезно?

Решение

Please find following working example -

BEGIN
       v_sql:='Create table empx (id int)';
       execute immediate v_sql; 
END;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top