Having an issue converting SQL to postgreSQL with ''' making huge strings - sql

CONCAT('ERROR - Portfolio '', ''' not found in br_portfolio and composite_member table')
My issue is that ''' is creating a huge string that goes on for many lines after it is, so I guess the problem is how do I create ' char as a string that is wrapped in ''?
Thanks

Maybe this is more of a comment, but for what it's worth some additional options for you.
If you have a long string that includes return characters and single quotes, you can always use string literals using $$:
select $ONE$I'm a dog$ONE$, $FOOT$Hello,
Hambone's Dog$FOOT$
Hopefully you can see what goes inside the $$ doesn't matter -- it just has to match the beginning and end of the literal.
Second comment: I really like the format function in Pg. It's cleaner, in my opinion, than doing concat or multiple concat operators:
select format ('Eating too much %s is dangerous', 'cake')
So, combining these two, I wonder if this will help make your code cleaner/easier:
create table test (portfolio varchar(20));
insert into test values ('foot'), ('ball');
select
format ($EE$ERROR - Portfolio '%s' not found in br_portfolio$EE$, portfolio)
from test;

Related

How do I correctly implement quotename in SQL Server?

Background Info:
I have a stored procedure that is populating an SSRS report. The SSRS report is ran and exported as a CSV. It is then opened as textfile and ran through a 3 party vendor application.
The output of the text book should look like this:
lid, status, i_flag,Count, pDate, iDate
62558633,"Text Value","08/16",11,"08/16","08/16"
78013526,"Text Value","",,"08/16""08/16"
My results look like this:
lid, status, i_flag,Count,pDate,iDate
19007442,"'Dir,MgmtII'",'',2,'','02/16'
17343623,'Text','',0,'11/15','02/16'
Now the code that I'm using is:
SELECT
quotename(isnull(i_flag,''''), '''') as i_flag,
isnull(lid, 0) as lid,
quotename(isnull(status,''''), '''') as status,
isnull(Count, 0) as Count,
quotename(isnull(p_Date,''''), '''') as p_Date,
quotename(isnull(i_Date,''''), '''') as i_Date
FROM
#Table
Any ideas on how I can fix this. Been stumped on this for a bit. Thanks.
If I'm understanding your question correctly (which I'm quite possibly not), I think you want:
SELECT
QUOTENAME(ISNULL(i_flag,''), '"') AS i_flag,
ISNULL(lid, 0) AS lid,
QUOTENAME(ISNULL([status],''), '"') AS [status],
ISNULL([Count], 0) AS [Count],
QUOTENAME(ISNULL(p_Date,''), '"') AS p_Date,
QUOTENAME(ISNULL(i_Date,''), '"') AS i_Date
FROM
#Table
It sounds like you have some values in fields which you wish to wrap in double quotes " for the purpose of exporting to CSV, plus in some cases the values in these fields might be NULL.
My suggestion above handles this by first using ISNULL to replace any NULL values with an empty string and then using QUOTENAME to wrap the resultant value in double quotes.
The crucial differences to your posted code are:
When using ISNULL I replace the NULL with an empty string '' instead of a string containing a single quote character '''' (two consecutive single quotes within a string represent an escaped literal single quote character)
When using QUOTENAME to wrap the values in double quotes, I specify a string containing a double quote '"' in the second parameter, instead of a string containing a single quote character ''''.
I hope that helps you - if you're still having problems, perhaps you could provide some sample rows from your #Table temp table and the output you're expecting from the query so people can help you further.
As an aside, it's not good practice to use SQL reserved keywords like status or count as column names or aliases, but if you must, I'd recommend enclosing them in brackets (i.e. [status]) for readability (especially in SSMS or any IDE with SQL syntac highlighting or colour-coding) as I have done above.

Select query that displays Joined words separately, not using a function

I require a select query that adds a space to the data based on the placement of the capital letters i.e. 'HelpMe' using this query would be displayed as 'Help Me' . Note i cannot use a stored function to do this the it must be done in the query itself. The Data is of variable length and query must be in SQL. Any Help will be appreciated.
Thanks
You need to use user defined function for this until MS give us support for regular expressions. Solution would be something like:
SELECT col1, dbo.RegExReplace(col1, '([A-Z])',' \1') FROM Table
Aldo this would produce leading space that you can remove with TRIM.
Replace regular expresion function:
http://connect.microsoft.com/SQLServer/feedback/details/378520
About dbo.RegexReplace you can read at:
TSQL Replace all non a-z/A-Z characters with an empty string
Assume if you are using Oracle RDBMS, you use the following,
REGEX_REPLACE
SELECT REGEXP_REPLACE('ILikeToWatchCSIMiami',
'([A-Z.])', ' \1')
AS RX_REPLACE
FROM dual
;
Managed to get this output: * SQLFIDDLE
But as you see it doesn't treat well on words such as CSI though.

SQL -- SELECT statement -- concatenate strings to

I have an SQL question. Everything works fine in the below SELECT statement except the portion I have highlighted in bold. What I'm trying to do is allow the user to search for a specific Rule within the database. Unfortunately, I do not actually have a Rule column, and so I need to concatenate certain field values to create a string with which to compare to the user's searchtext.
Any idea why the part in bold does not work? In theory, I would like this statement to check for whether the string "Rule " + part_num (where part_num is the value contained in the part_num field) equals the value of searchtext (the value of searchtext is obtained from my PHP script).
I did some research on concatenating strings for SQL purposes, but none seem to fit the bill. Does someone out there have any suggestions?
SELECT id,
part_num,
part_title,
rule_num,
rule_title,
sub_heading_num,
sub_heading,
contents
FROM rules
WHERE part_title LIKE "%'.$searchtext.'%"
OR rule_title LIKE "%'.$searchtext.'%"
OR sub_heading LIKE "%'.$searchtext.'%"
OR contents LIKE "%'.$searchtext.'%"
OR "rule" + part_num LIKE "%'.$searchtext.'%" --RULE PLUS PART_NUM DOESN'T WORK
ORDER BY id;
Since you didn't specify which DB your using, I'm going to assume SQL Sever.
Strings are specified in SQL Server with single quotes 'I'm a string', not double quotes.
See + (String Concatenation) on MSDN for examples.
Another possibility is that part_num is a numeric. If so, cast the number to a string (varchar) before concatenating.

How do you convert from scientific notation in Oracle SQL?

We are trying to load a file created by FastExport into an oracle database.
However the Float column is being exported like this: 1.47654345670000000000 E010.
How do you configure SQL*Loader to import it like that.
Expecting Control Script to look like:
OPTIONS(DIRECT=TRUE, ROWS=20000, BINDSIZE=8388608, READSIZE=8388608)
UNRECOVERABLE LOAD DATA
infile 'data/SOME_FILE.csv'
append
INTO TABLE SOME_TABLE
fields terminated by ','
OPTIONALLY ENCLOSED BY '"' AND '"'
trailing nullcols (
FLOAT_VALUE CHAR(38) "???????????????????",
FILED02 CHAR(5) "TRIM(:FILED02)",
FILED03 TIMESTAMP "YYYY-MM-DD HH24:MI:SS.FF6",
FILED04 CHAR(38)
)
I tried to_number('1.47654345670000000000 E010', '9.99999999999999999999 EEEE')
Error: ORA-01481: invalid number format model error.
I tried to_number('1.47654345670000000000 E010', '9.99999999999999999999EEEE')
Error: ORA-01722: invalid number
These are the solutions I came up with in order of preference:
to_number(replace('1.47654345670000000000 E010', ' ', ''))
to_number(TRANSLATE('1.47654345670000000000 E010', '1 ', '1'))
I would like to know if there are any better performing solutions.
As far as I'm aware there is no way to have to_number ignore the space, and nothing you can do in SQL*Loader to prepare it. If you can't remove it by pre-processing the file, which you've suggested isn't an option, then you'll have to use a string function at some point. I wouldn't expect it to add a huge amount of processing, above what to_number will do anyway, but I'd always try it and see rather than assuming anything - avoiding the string functions sounds a little like premature optimisation. Anyway, the simplest is possibly replace:
select to_number(replace('1.47654345670000000000 E010',' ',''),
'9.99999999999999999999EEEE') from dual;
or just for display purposes:
column num format 99999999999
select to_number(replace('1.47654345670000000000 E010',' ',''),
'9.99999999999999999999EEEE') as num from dual
NUM
------------
14765434567
You could define your own function to simplify the control file slightly, but not sure it'd be worth it.
Two other options come to mind. (a) Load into a temporary table as a varchar, and then populate the real table using the to_number(replace()); but I doubt that will be any improvement in performance and might be substantially worse. Or (b) if you're running 11g, load into a varchar column in the real table, and make your number column a virtual column that applies the functions.
Actually, a third option... don't use SQLLoader at all, but use the CSV file as an external table, and populate your real table from that. You'll still have to do the to_number(replace()) but you might see a difference in performance over doing it in SQLLoader. The difference could be that it's worse, of course, but might be worth trying.
Change number width with "set numw"
select num from blabla >
result >> 1,0293E+15
set numw 20;
select num from blabla >
result >> 1029301200000021
Here is the solution I went with:
OPTIONS(DIRECT=TRUE, ROWS=20000, BINDSIZE=8388608, READSIZE=8388608)
UNRECOVERABLE LOAD DATA
infile 'data/SOME_FILE.csv'
append
INTO TABLE SOME_TABLE
fields terminated by ','
OPTIONALLY ENCLOSED BY '"' AND '"'
trailing nullcols (
FLOAT_VALUE CHAR(38) "REPLACE(:FLOAT_VALUE,' ','')",
FILED02 CHAR(5) "TRIM(:FILED02)",
FILED03 TIMESTAMP "YYYY-MM-DD HH24:MI:SS.FF6",
FILED04 CHAR(38)
)
In my solution the conversion to a number is implicit:
"REPLACE(:FLOAT_VALUE,' ','')"
In Oracle 11g, it's not needed to convert numbers specially.
Just use integer external in the .ctl-file:
I tried the following in my Oracle DB:
field MYNUMBER has type NUMBER.
Inside .ctl-file I used the following definition:
MYNUMBER integer external
In the datafile the value is: MYNUMBER: -1.61290E-03
As for the result: sqlldr loaded the notation correctly: MYNUMBER field: -0.00161290
I am not sure if it's a bug or a feature; but it works in Oracle 11g.

Can anyone help me write a sql query

jkdfhdjfhjh&name=ijkjkjkjkjkjk&id=kdjkjkjkjkjkjjjd&class=kdfjjfjdhfjhf
The above string has some characters starting with & and ending with =
for example we have &name= and I just need this from the above string.
similarly I need &id=, &class=
I need the output under a single column.
Final Extract
----------------------
&id=, &class=, &name=
can anyone help me out in writing a query for this.
You could try this :
select regexp_replace('jkdfhdjfhjh&name=ijkjkjkjkjkjk&id=kdjkjkjkjkjkjjjd&class=kdfjjfjdhfjhf', '\\w*?(&.*?=)\\w+((?=&)|$)', '\\1, ', 'g');
result:
regexp_replace
-------------------------
&name=, &id=, &class=,
Then it's up to you to remove the last ,.
The regexp_replace function is available in version 8.1 and after.
If you want the values along with each variable, I would implement this by splitting on "&" into an array and then taking a slice of the desired elements:
SELECT (string_to_array('jkdfhdjfhjh&name=ijkjkjkjkjkjk&id=kdjkjkjkjkjkjjjd&class=kdfjjfjdhfjhf','&'))[2:4];
Output in PostgreSQL 8.4 (array type):
{name=ijkjkjkjkjkjk,id=kdjkjkjkjkjkjjjd,class=kdfjjfjdhfjhf}
The example string is very wide so here's the general form to show the array slicing more clearly:
SELECT ((string_to_array(input_field,'&'))[2:4];
NOTE: You must have the extra parentheses around the string_to_array() call in order for the array slicing to work--you'll get an error otherwise.