Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debug SQL in pgAdmin when SQL contains variables

In SQL Server I could copy sql code out of an application and paste it into SSMS, declare & assign vars that exist in the sql and run. yay great debugging scenario.

E.g. (please note I am rusty and syntax may be incorrect):

declare @x as varchar(10)
set @x = 'abc'
select * from sometable where somefield = @x

I want to do something similar with Postgres in pgAdmin (or another postgres tool, any recommendations?) where I can just drop my SQL (params & all) into something that will run against Postgres DB.

I realise you can create pgscript, but it doesn't appear to be very good, for example, if I do the equivalent of above, it doesn't put the single quotes around the value in @x, nor does it let me by doubling them up and you don't get a table out after - only text...

Currently I have a piece of SQL someone has written that has 3 unique variables in it which are used around 6 times each...

So the question is how do other people debug SQL efficiently, preferably in a similar fashion to my SQL Server days.

like image 941
Mr Shoubs Avatar asked Nov 06 '22 12:11

Mr Shoubs


1 Answers

You can achieve this using the PREPARE, EXECUTE, DEALLOCATE commands for handling statements, which is really what we are talking about here.

For example:

PREPARE test AS SELECT * FROM users WHERE first_name = $1;
EXECUTE test ('paul');
DEALLOCATE test;

Perhaps not as graphical as some may like, but certainly workable.

like image 79
paulkmoore Avatar answered Nov 11 '22 04:11

paulkmoore