動的SQL

declare

tabname varchar2(100);
begin
tabname := 'tab98';
execute immediate 'create table '||tabname||'(col1 int)';
end;
/

 

https://qiita.com/hand10ryo/items/6f7c9669ba8870cb16a9
https://gene.hatenablog.com/entry/20100608/1275994173


set @tabname := 'tab1';

set @q := concat(" select * from ",@tabname," order by 1 ");
prepare stmt from @q;
execute stmt;
deallocate prepare stmt;

 

drop table tab1,tab2,tab3,tabname;

create table tabname(col1 varchar(200));
insert into tabname values('tab1'),('tab2'),('tab3');

create table tab1 (col1 int);
insert into tab1 values(11),(12),(13);
create table tab2 (col1 int);
insert into tab2 values(21),(22),(23);
create table tab3 (col1 int);
insert into tab3 values(31),(32),(33);

select * from tab1;
select * from tab2;
select * from tab3;

do $$
declare
r record;
begin
for r in select col1 from tabname order by col1
loop
execute 'truncate table ' || quote_ident(r.col1) ;
execute 'insert into ' || quote_ident(r.col1) || ' values(999) ' ;
end loop;
exception
when division_by_zero then
raise notice 'caught division_by_zero';
end
$$
;

 

https://docs.microsoft.com/ja-jp/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-2017
http://akisan123.hatenablog.com/entry/20110705/1309863094


execute (N'select * from dbo.tab1')

 

execute sp_executesql
N'select * from dbo.tab1 where col1 = @col1',
N'@col1 int', @col1 = 123