woensdag 27 november 2013

pl sql declare and use variable while concat string

Introduction

In this case I did not do anything with java but with sql. The interesting part is that, as a java developer I do not do these things every day. So lets make it memoirable.
I needed to couple two tables by ip adress of the client. But There was no foreign key to deal with. The first table had all the parts of the ip adress as numbers addr1 would be 127 addr2 would be 0 addr3 would be 0 and addr4 would be 7. In the other table the whole ip adress would appear like '127.0.0.1'. The whole selection would have a where clause by name from another table.

Solving the problem

So the first thing I needed to do was declare a variable and add the value of the ips to it with a selection over two tables based on the name of the compagny that looks like:

set serveroutput on --makes it printable
declare
  v_line varchar2(40); -- declares the var v_line
  begin
    select TO_CHAR(addr1)|| '.' || TO_CHAR(addr2) || '.' || TO_CHAR(addr3) || '.' || TO_CHAR(addr4)into v_line from ip_adress join comp on ip_adress.comp_id = comp.id where comp.name = 'my compangy'; -- TO-CHAR converts the number into a string
   --the || are the concat commands.
 dbms_output.put_line (v_line) -- prints the ipadress;
  end;
   / -- this is like an end sign dont forget it.

So now we have variable filled with a selection from the database.
In the following line You can do  a selection based on the variable:

 select * from STAT_HOURLY_SESSIONS_COUNT where STAT_HOURLY_SESSIONS_COUNT.machine = :v_line;  -- dont forget the : before the variable.

Declare the variable, and execute the query in one run.
Conclusion

If you want to build a database read the normalisation rules by Codd. Doing it like this is not improving the simpleness and performance of your database actions.

Have fun.

Geen opmerkingen:

Een reactie posten