0

I want to execute a dynamic SQL statement, which searches for names whose last name is always a constant and first name is a variable. Here is a query I have written for selecting a row with name='Test lastname'.

EXECUTE 'SELECT name FROM users 
        WHERE name=$1 lastname'
USING ('Test');  

This generates a syntax error. Is it possible to do this?

3
  • What you mean when say "constant"? Hard coded value ? Commented Jun 5, 2017 at 13:10
  • to debug: store your sql to a variable and write out the variable so you can see what was built. Commented Jun 5, 2017 at 13:12
  • @OtoShavadze yes Commented Jun 5, 2017 at 13:14

1 Answer 1

1

I think you need something like this:

EXECUTE 'SELECT user_id FROM users 
        WHERE name=$1'
USING  Test||' lastname' ; 

Here Test is variable and 'lastname' is hard coded value

Also another way is as @JorgeCampos mentioned:

...WHERE name=$1 || '' lastname''' USING 'Test';
Sign up to request clarification or add additional context in comments.

12 Comments

Almost... since lastname seems to be a column from the users table I think he wants: ...WHERE name=$1 || lastname' USING 'Test '
@JorgeCampos - As I understand, he have only name column and stores both first and last names there
I want rows with name = 'Test lastname' where the last name is always 'lastname' and first name is a variable.
There is no difference as of now. By the time he asked your answer was still with the 'Test ' || lastname variation (I think). And since you provide the right way (even though slightly different) I choose just to collaborate with your answer :) cheers
@JorgeCampos - Ah, I understand now, your comment was before... Thank you again :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.