Home > Mobile >  Run SQL Script programatically
Run SQL Script programatically

Time:11-04

I have a sql script like this:

select id,
       name,
       address,
       age,
       sex
from table1
left join table2 <condition>
left join table3 <condition>
where name = 'Harry Potter';

Is there a way that I call and run this script but change the name of interest without editing the original script? For instance, I want to run this line instead.

where name = 'Lebron James'

I am using PostgreSQL.

Thanks in advance.

CodePudding user response:

You can include your query in a function while replacing the name string by an input parameter input_name :

CREATE OR REPLACE FUNCTION test (input_name text)
RETURNS table (id int, name text, address text, age int, sex text) 
LANGUAGE sql AS
$$
select id,
       name,
       address,
       age,
       sex
from table1
left join table2 <condition>
left join table3 <condition>
where name = input_name  ;
$$

Then SELECT * FROM test('Lebron James') should return the right query result.

  • Related