使用Unicode选择SQL

时间:2010-11-26 00:47:37

标签: postgresql utf-8

我有编码UTF-8,collat​​ion和ctype ru_RU.UTF-8的数据库。表格结构 - idkeyvalue。插入一行:

1 | size | --- "\xD0\xA0\xD0\xB0\xD0\xB7\xD0\xBC\xD0\xB5\xD1\x80"|

我执行时

SELECT E'--- "\xD0\xA0\xD0\xB0\xD0\xB7\xD0\xBC\xD0\xB5\xD1\x80"';

在控制台中,我得到了正确的输出

   ?column?   
   --------------
    --- "Размер"
   (1 row)

但是当我试图执行

select "value" from "translations" where "key"='size';

我得到了

   value                          
   --------------------------------------------------------
    --- "\xD0\xA0\xD0\xB0\xD0\xB7\xD0\xBC\xD0\xB5\xD1\x80"
   (1 row)

如何获取非转义字符串?

CREATE TABLE translations (
    id serial NOT NULL,
    "key" character varying(255) NOT NULL,
    "value" text,
    CONSTRAINT translations_pkey PRIMARY KEY (id) )
 WITH ( OIDS=FALSE );
 ALTER TABLE translations OWNER TO user;
 CREATE UNIQUE INDEX index_translations_on_key ON translations USING btree (key);

2 个答案:

答案 0 :(得分:2)

CREATE OR REPLACE FUNCTION eval(text) RETURNS text AS
$BODY$  
DECLARE
  s text;
  r text;
BEGIN
  s := 'select ' || $1 ;
  execute s into r;
  return r;
END;
$BODY$ LANGUAGE 'plpgsql' VOLATILE;

select eval(E'E\'' || "value" || E'\'') from translations where key = 'size' and "value" IS NOT NULL;

看起来很糟糕,但有效:)

答案 1 :(得分:0)

我不明白你为什么要在数据库中存储转义值,但据我所知,解码函数应该做你想要的。

SELECT decode(value, 'hex')
FROM translations;