September 17th, 2012, 12:35 PM
Select * where something = "all"
I am working on a GUI that will be used to query a database. The table I am working on has 34 columns and the user will have the option to enter a value for any of the columns or leave them empty. I want to only use one sprintf statement to query the database so is there a way that if they didnt enter a value I can set the query to understand I want all values for that particular column.
snprintf(sqlEntry,sizeof(sqlEntry),"select * from main.myTable where length = 100 AND width = ALL");
results = PQexec(sqlEntry);
*I know that I can just do where length = 100 and not put width in at all but then I would need 3 different snprintf statements depending on if they user inserted a length or width or both. 3 different snprintf's for 2 variables is doable but I am working with 34 columns so the amount of coding for that is too much. Any help is much appreciated
September 17th, 2012, 01:01 PM
Construct the query dynamically. I don't know the language you're using, but I would make a list of the 34 columns, loop through it and whenever the value for this column is set, you add " AND (the column name) = (the value)" to the query string.
September 17th, 2012, 01:20 PM
Originally Posted by Jacques1
That is a very good idea I wasn't thinking of being creative in my c/obj-c. I just know that you can do "select *" in postgres and it is basically select all so I was hoping there was something similar for individual columns. However, your solution will basically do exactly what I want so thank you.