2017-04-02 46 views
1

PSQL(9.6.1,9.5.5服務器)使用變量

員工

 Column  |   Type    |       Modifiers       | Storage | Stats target | Description 
----------------+-----------------------------+-----------------------------------------------------------------+----------+--------------+---- --------- 
employee_id | integer      | not null default nextval('employees_employee_id_seq'::regclass) | plain |    | 
first_name  | character varying(20)  |                 | extended |    | 
last_name  | character varying(25)  | not null              | extended |    | 
email   | character varying(25)  | not null              | extended |    | 
phone_number | character varying(20)  |                 | extended |    | 
hire_date  | timestamp without time zone | not null              | plain |    | 
job_id   | character varying(10)  | not null              | extended |    | 
salary   | numeric(8,2)    |                 | main  |    | 
commission_pct | numeric(2,2)    |                 | main  |    | 
manager_id  | integer      |                 | plain |    | 
department_id | integer 

對於自我教育,我想用一個變量。

這個請求的結果會適合我:

hr=> select last_name, char_length(last_name) as Length from employees where substring(last_name from 1 for 1) = 'H' order by last_name; 
last_name | length 
-----------+-------- 
Hartstein |  9 
Higgins |  7 
Hunold |  6 
(3 rows) 

但自我教育,我想用一個變量:

\set chosen_letter 'H' 
hr=> select last_name, char_length(last_name) as Length from employees where substring(last_name from 1 for 1) = :chosen_letter order by last_name; 
ERROR: column "h" does not exist 
LINE 1: ...ployees where substring(last_name from 1 for 1) = H order by... 
                  ^

那些撇號似乎毀了一切。我無法應付這個問題。

你能幫我理解如何使用變量來獲得如上的結果嗎?

回答

2

嘗試使用:

\set chosen_letter '''H'''