PostgreSql text to varchar with concat_ws - postgresql

I am using PostgreSQL and I need fields as strings not text.
Here is the statement
select AutoNbr,
concat_ws(', ', Site_Street, Site_City, Site_Country, Site_PostCode) as cFullAddress , Order_Date
from Porder
What I need is the cFullAddress to be a varchar not a text field.

According to documents:
If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.
In addition, PostgreSQL provides the text type, which stores strings of any length. Although the type text is not in the SQL standard, several other SQL database management systems have it as well.
But you can cast it into varchar;
select AutoNbr,
concat_ws(', ', Site_Street, Site_City, Site_Country, Site_PostCode)::varchar as cFullAddress , Order_Date,
CAST(concat_ws(', ', Site_Street, Site_City, Site_Country, Site_PostCode) as VARCHAR)
from Porder
Related link for using cast: type cast
Difference between text and varchar (character varying)

Related

Data Migration from DB2 to PostgreSQL using AWS DMS - Varchar fields are showing trailing spaces

We are migrating DB2 data to PostgreSQL 11.x using AWS DMS, we have varchar fields in db2 with trailing spaces and without any TRIM these fields working fine when we are using these fields in a WHERE clause. I think DB2 internally trimming them as these are varchar fields. But after moving to PostgreSQL these fields are not working without TRIM and also some times these giving unexpected results even if you use TRIM. below is the detailed problem.
Source: DB2 - RECIP_NUM -- VARCHAR(10) -- 'ST001 '
select RECIP_NUMBER, SERV_TYPE, LENGTH(SERV_TYPE) AS before_trim_COL_LENGTH, LENGTH(trim(SERV_TYPE)) AS after_trim_COL_LENGTH
from serv_type rst
WHERE SERV_TYPE = 'ST001' -- THIS WORKS FINE WITHOUT TRIM
Output:Output of DB2
Target: PGSQL -- RECIP_NUM -- VARCHAR(10) -- 'ST001 '
select RECIP_NUMBER, SERV_TYPE, LENGTH(SERV_TYPE) AS COL_LENGTH
from serv_type rst
WHERE trim(SERV_TYPE) = 'ST001' -- THIS IS NOT GIVING ANY OUTPUT WITHOUT TRIM
Output: Output of PostgreSQL
Is there any way we can tell PostgreSQL to ignore the trailing spaces of a VARCHAR Column?
Postgres doesn't follow the SQL standard, which requires the shorter string be padded, when comparing VARCHAR or TEXT strings; it only pads the CHAR strings. Therefore, you can use ...WHERE SERV_TYPE::char = 'ST001'::char to simulate the Db2 behaviour. Note though that this will preclude the use of index on SERV_TYPE, same as when using trim(SERV_TYPE).

SQL Command to insert Chinese Letters

I have a database with one column of the type nvarchar. If I write
INSERT INTO table VALUES ("玄真")
It shows ¿¿ in the table. What should I do?
I'm using SQL Developer.
Use single quotes, rather than double quotes, to create a text literal and for a NVARCHAR2/NCHAR text literal you need to prefix it with N
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE table_name ( value NVARCHAR2(20) );
INSERT INTO table_name VALUES (N'玄真');
Query 1:
SELECT * FROM table_name
Results:
| VALUE |
|-------|
| 玄真 |
First, using NVARCHAR might not even be necessary.
The 'N' character data types are for storing data that doesn't 'fit' in the database's defined character set. There's an auxiliary character set defined as the NCHAR Character set. It's kind of a band aid - once you create a database it can be difficult to change its character set. Moral of this story - take great care in defining the Character Set when creating your database and do not just accept the defaults.
Here's a scenario (LiveSQL) where we're storing a Chinese string in both NVARCHAR and VARCHAR2.
CREATE TABLE SO_CHINESE ( value1 NVARCHAR2(20), value2 varchar2(20 char));
INSERT INTO SO_CHINESE VALUES (N'玄真', '我很高興谷歌翻譯。' )
select * from SO_CHINESE;
Note that both the character sets are in the Unicode family. Note also I told my VARCHAR2 string to hold 20 characters. That's because some characters may require up to 4 bytes to be stored. Using a definition of (20) would give you only room to store 5 of those characters.
Let's look at the same scenario using SQL Developer and my local database.
And to confirm the character sets:
SQL> clear screen
SQL> set echo on
SQL> set sqlformat ansiconsole
SQL> select *
2 from database_properties
3 where PROPERTY_NAME in
4 ('NLS_CHARACTERSET',
5 'NLS_NCHAR_CHARACTERSET');
PROPERTY_NAME PROPERTY_VALUE DESCRIPTION
NLS_NCHAR_CHARACTERSET AL16UTF16 NCHAR Character set
NLS_CHARACTERSET AL32UTF8 Character set
First of all, you should to establish the Chinese character encoding on your Database, for example
UTF-8, Chinese_Hong_Kong_Stroke_90_BIN, Chinese_PRC_90_BIN, Chinese_Simplified_Pinyin_100_BIN ...
I show you an example with SQL Server 2008 (Management Studio) that incorporates all of this Collations, however, you can find the same characters encodings in other Databases (MySQL, SQLite, MongoDB, MariaDB...).
Create Database with Chinese_PRC_90_BIN, but you can choose other Coallition:
Select a Page (Left Header) Options > Collation > Choose the Collation
Create a Table with the same Collation:
Execute the Insert Statement
INSERT INTO ChineseTable VALUES ('玄真');

referencing parameters on stored procedures in PostgreSQL

I'm Converting some SQLServer stored procedures and I have a problem that I can't solve.
That's SQLServer function:
CREATE FUNCTION [dbo].[getViewNodeHierarchyAux](#pivot varchar(255), #parents varchar(max))
RETURNS #view TABLE (PARENT_OID varchar(255), CHILD_OID varchar(255))
...
insert into #view select F.* from BTREENODES_NODEHIERARCHY T cross apply [dbo].getViewNodeHierarchyAux(T.CHILD_OID,#parents) F where T.PARENT_OID=#pivot;
And that's the conversion I have thought in PostgreSQL:
CREATE OR REPLACE FUNCTION getviewnodehierarchyauxprueba(IN pivot character varying, IN parents character varying)
...
RETURNS TABLE(test_parent_oid character varying, test_child_oid character varying)
return query (select F.* from BTREENODES_NODEHIERARCHY T cross join getviewnodehierarchyprueba(T.CHILD_OID,parents) F WHERE T.PARENT_OID=pivot);
PgAdmin tells me that there's no valid reference to table 't' in 'from' clause. And if I write it this way
getviewnodehierarchyprueba((select CHILD_OID from BTREENODES_NODEHIERARCHY),parents)
It returns more than one record and it doesn't work. Any ideas? thank you!
PostgreSQL doesn't allow use a value of joined relation as parameter for second relation in joining. It will be available in 9.3 with LATERAL subselect. It is a first issue. Second issue - subselect can return only one row
(select CHILD_OID from BTREENODES_NODEHIERARCHY)
probably returns more than one row
You don't need wait to 9.3 - use a CTE (Common Table Expressions) instead for processing some recursive data.

Querying a SQL Server 2008 table to find values in a column containing Unicode characters

I've run into a problem in a project I'm working on: some of the string values in a specific SQL Server 2008 table column contain Unicode characters. For example, instead of a dash some strings will instead contain an EM DASH (http://www.fileformat.info/info/unicode/char/2014/index.htm).
The column values that contain Unicode characters are causing problems when I send HTTP requests to a third-party server. Is there a way to query what rows contain one-or-more Unicode characters, so I can at least begin to identify how many rows need to be fixed?
You want to find all strings that contain one or more characters outside ASCII characters 32-126.
I think this should do the job.
SELECT *
FROM your_table
WHERE your_column LIKE N'%[^ -~]%' collate Latin1_General_BIN
One way you can do it is to see which rows no longer equal themselves when converted to a datatype that doesn't support unicode.
CREATE TABLE myStrings (
string nvarchar(max) not null
)
INSERT INTO myStrings (string)
SELECT 'This is not unicode' union all
SELECT 'This has '+nchar(500)+' unicode' union all
SELECT 'This also does not have unicode' union all
SELECT 'This has lots of unicode '+nchar(600)+nchar(700)+nchar(800)+'!'
SELECT cast(string as varchar)
FROM myStrings
SELECT *
FROM myStrings
WHERE cast(cast(string as varchar(max)) as nvarchar(max)) <> string
SELECT *
FROM your_table
WHERE your_column LIKE N'%[^ -~]%' collate Latin1_General_BIN
finds all strings that contain one or more characters within ASCII characters 32-126.
I thought the purpose was to find strings where ASCII characters are not in the range 32-126?
NOT is possible with LIKE. Wouldn't this work?
SELECT *
FROM your_table
WHERE your_column NOT LIKE N'%[^ -~]%'
No collate required.

How to find out the length of a varchar parameter in a postgres function

I'm trying to find out the parameter length for a varchar parameter passed into a postgres function.
The SQL I have just now has no values in the character_maximum_length column where I would have expected to find this value
SELECT *
FROM information_schema.parameters
WHERE specific_schema='public'
AND specific_name like 'foo'
ORDER BY ordinal_position
I don't think postgresql keeps this information. If I create function foo(varchar(100)) returns boolean ... and then dump the schema with pg_dump, I find:
CREATE FUNCTION foo(character varying) RETURNS boolean
LANGUAGE sql
AS $$select true$$;
The '100' specification is gone. And passing a 150-character string to foo(varchar) is not trapped or anything. By contrast, if I create a domain based on varchar(100) and define the function in terms of that, then passing an overlong string is trapped.