How to select a column to appear with two single quote in the field - postgresql

Here is my postgresql query
select 'insert into employee(ID_NUMBER,NAME,OFFICE) values ('''||ID_NUMBER||''','''||NAME||''','''||replace(DESIGNATION,'&','and')||''','''||replace(DEPT_NAME,'&','and')||''')' as col
from icare_employee_view
where id_number='201403241'
order by name;
output
insert into employee(ID_NUMBER,NAME,OFFICE) values ('201403241','ABINUMAN, JOSEPHINE CALLO','Assistant AGrS Principal for Curriculum and Instruction','AGrS Principal's Office')
but I need 'AGrS Principal's Office' to be 'AGrS Principal''s Office'
but I need 'AGrS Principal's Office' to be 'AGrS Principal''s Office'
any suggestions or sol'n is highly appreciated on how to fix my PostgreSQL query

Hi check this from pgDocs:
quote_literal ( text ) → text
Returns the given string suitably quoted to be used as a string
literal in an SQL statement string. Embedded single-quotes and
backslashes are properly doubled. Note that quote_literal returns null
on null input; if the argument might be null, quote_nullable is often
more suitable. See also Example 43.1.
quote_literal(E'O'Reilly') → 'O''Reilly'

Related

Postgresql if null in field,the whole sql is null

I use this sql to execute sql:
v_sql4 :='
INSERT INTO public.rebatesys(head,contract_no,history_no,f_sin,line_no,s_line_no,departmentcd,catagorycd,jan,seriescd,f_exclude, f_del,ins_date,ins_time,ins_user_id,ins_func_id,ins_ope_id,upd_date,upd_time,upd_user_id,upd_func_id,upd_ope_id)
VALUES (0, '''||v_contract_no||''', '||v_history_no||',1, '||v_line_no||', '||v_down_s_line_no||', '||coalesce(v_deptCD,null)||', '||0||', '''||v_singleJan||''','''||0||''','||v_fExclude||',
0, current_date, current_time, '||v_ins_user_id||', 0, 0,
current_date,current_time,'||v_upd_user_id||',0, 0);';
RAISE NOTICE 'v_sql4 IS : %', v_sql4;
EXECUTE v_sql4;
But when field "v_deptCD" is null,the whole sql is null,even I use coalesce,I still can't do id, the out put is :
NOTICE: v_sql4 IS : <NULL>
How to fix it?
When v_deptCD is null, you want to replace it by the string 'null', not the keyword.
', '||coalesce(v_deptCD,'null')||', '
You can use this
case when v_deptCD notnull then v_deptCD else null end
or use this for string concatination inside sql
concat(field1, ', ', field2)
Alternative approach to JGH solution is to use function format(your_string, list, of, values), it can ignore NULL values, but has the option to display them as NULL if you use %L in your format string. It will however single quote numbers if you use that format specifier, requiring casting in some cases.
Format arguments according to a format string. This function is similar to the C function sprintf. See Section 9.4.1.
But in my opinion best solution is to use USING clause and pass values in there. It looks kinda like prepared statement, protects you from SQL Injection, but does not cache plans like prepared statements. There are simple examples on how to do this in documentation for executing dynamic commands.
EXECUTE 'SELECT count(*) FROM mytable WHERE inserted_by = $1 AND inserted <= $2'
INTO c
USING checked_user, checked_date;

invalid input syntax for integer: "9Na_(2)SO_(4)"

I'm trying to insert a alphanumeric value in a table:
INSERT INTO solution (solution, nextsolution) VALUES
('9Na_(2)SO_(4)', NULL), ('2Ni(OH)_(3)', (SELECT id FROM solution WHERE solution='9Na_(2)SO_(4)' & nextsolution=null));
solution is of type text and nextsolution is an integer. Unfortunately postgresql doesn't allow me to do the WHERE clause. It gives me the error:
ERROR: invalid input syntax for integer: "9Na_(2)SO_(4)"
LINE 9: ...OH)_(3)', (SELECT id FROM solution WHERE solution='9Na_(2)SO...
How can I solve this?
The issue is that the statement in the where clause: '9Na_(2)SO_(4)' & nextsolution=null tries to do a bitwise and (&) operation on the string and this won't work (and probably isn't what you want anyway).
Looking at your query I think what you want is to first insert the value '9Na_(2)SO_(4)' and then the value '2Ni(OH)_(3)' with the id of the previous inserted row.
You need to do this as two statements and use a different syntax. This should do what you want:
INSERT INTO solution (solution, nextsolution) VALUES (
'9Na_(2)SO_(4)',
NULL
);
INSERT INTO solution (solution, nextsolution) VALUES (
'2Ni(OH)_(3)',
(SELECT id FROM solution WHERE solution='9Na_(2)SO_(4)' and nextsolution is null)
);
You need to use AND instead of & to join your WHERE clause - an ampersand (&) is used for bitwise operations.

Escaping formula for Grails derived properties

Grails offers derived properties to generate a field from a SQL expression using the formula mapping parameter:
static mapping = {
myfield formula: "field1 + field2"
}
I'm trying to use the formula parameter with a PostgreSQL database to make a concatenated field. The syntax is a little strange since PostgreSQL 8.4 doesn't yet support concat_ws:
static mapping = {
myfield formula: "array_to_string(array[field1, field2],' ')"
}
The produced SQL shown with loggingSql = true in the DataSource config has the table prefix inserted into some strange places:
select table0_.field1 as field1_19_0_,
table0_.field2 as field2_19_0_,=
array_to_string(table0_.array[field1, table0_.field2], ' ') as formula0_0_
from test_table table0_ where table0_.id=?
The table prefix errantly appears before array but not before field1 in the derived formula. Is there a way to escape the prefix or correct this behavior more explicitly?
This is just an issue with parsing the formula syntax. GORM tries to insert the table prefix for unquoted expressions not followed by parens, so the ARRAY[] notation trips it up.
My solution was to define the concat_ws function:
CREATE OR REPLACE FUNCTION concat_ws(separator text, variadic str text[])
RETURNS text as $$
SELECT array_to_string($2, $1);
$$ LANGUAGE sql;
The GORM formula parameter can now avoid the ARRAY[] syntax, and works as expected.
myfield formula: "concat_ws(' ', field1, field2)"
I had a very similar problem and solved it by adding single-quotes around the things that GORM was trying to prefix:
static mapping =
{
dayOfYear formula: " EXTRACT('DOY' FROM observed) "
}
GORM then produced this, which worked:
select
EXTRACT('DOY' FROM observed) as y1_
This may not work in all cases, but I hope it helps somebody.

Prevent trailing spaces during insert?

I have this INSERT statement and there seems to be trailing spaces at the end of the acct_desc fields. I'd like to know how to prevent trailing spaces from occurring during my insert statement.
INSERT INTO dwh.attribution_summary
SELECT d.adic,
d.ucic,
b.acct_type_desc as acct_desc,
a.begin_mo_balance as opening_balance,
c.date,
'fic' as userid
FROM fic.dim_members d
JOIN fic.fact_deposits a ON d.ucic = a.ucic
JOIN fic.dim_date c ON a.date_id = c.date_id
JOIN fic.dim_acct_type b ON a.acct_type_id = b.acct_type_id
WHERE c.date::timestamp = current_date - INTERVAL '1 days';
Use the PostgreSQL trim() function. There is trim(), rtrim() and ltrim().
To trim trailing spaces:
...
rtrim(b.acct_type_desc) as acct_desc,
...
If acct_type_desc is not of type text or varchar, cast it to text first:
...
rtrim(b.acct_type_desc::text) as acct_desc,
...
If acct_type_desc is of type char(n), casting it to text removes trailing spaces automatically, no trim() necessary.
Besides what others have said, add a CHECK CONSTRAINT to that column, so if one forgets to pass the rtrim() function inside the INSERT statement, the check constraint won't.
For example, check trailing spaces (in the end) of string:
ALTER TABLE dwh.attribution_summary
ADD CONSTRAINT tcc_attribution_summary_trim
CHECK (rtrim(acct_type_desc) = acct_type_desc);
Another example, check for leading and trailing spaces, and consecutive white spaces in string middle):
ALTER TABLE dwh.attribution_summary
ADD CONSTRAINT tcc_attribution_summary_whitespace
CHECK (btrim(regexp_replace(acct_type_desc, '\s+'::text, ' '::text, 'g'::text)) = acct_type_desc);
What is the type of acct_desc?
If it is CHAR(n), then the DBMS has no choice but to add spaces at the end; the SQL Standard requires that.
If it is VARCHAR(n), then the DBMS won't add spaces at the end.
If PostgresSQL supported them, the national variants of the types (NCHAR, NVARCHAR) would behave the same as the corresponding non-national variant does.

A Query to return Alphanumeric

Does any have any query that returns apha numerice values only
Sample
Select FirstName,Surname,NationalID From Contacts
Results
FirstName|Surname|NationalID
Tony |Smith |934&#fdsaf$34£51
Mary |Jones |655^!ffdat#389£2
Expected results
FirstName|Surname|NationalID
Tony |Smith |934fdsaf34£51
Mary |Jones |655ffdat389£2
In other words i want the query to return numbers and text only :. A-Z and 0-9 only remving '$%^&*(~>
You could try the patindex function. For example with just selecting the FirstName this will remove the first occurrence of non alphanumeric:
SELECT replace(FirstName, substring(FirstName, patindex('%[^a-zA-Z0-9]%', FirstName), 1), '') FROM CONTACTS
To expand this to removing all occurrences, move the patindex call into a function as mentioned here:
CREATE FUNCTION CleanVarchar(#Temp VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
WHILE PATINDEX('%[^a-zA-Z0-9]%', #Temp) > 0
SET #Temp = STUFF(#Temp, PATINDEX('%[^a-z^0-9]%', #Temp), 1, '')
RETURN #TEmp
END
Finally call the function
Select CleanVarchar(FirstName),CleanVarchar(Surname),CleanVarchar(NationalID) From Contacts
I don't think this is possible with T-SQL only in a neat way.
But you could easily expose such a functionality through a .NET Assembly to the SQL-Server.
There several examples on this topic over the net.
use Replace function of sql server
Sql Server Tips – Removing or Replacing non-alphanumeric characters in strings