What is the error you're getting? If no error, what's the expected behavior vs the actual behavior? Did you print out the sql statement after creating it? If not, do so. If so, please give the output.
Off the top of my head I notice that you're referencing a table P in your field list which isn't included in the query, and that when concatenating lines you've left out several spaces.