Apostrophe(') in SQL data,oracle 11g - sql

I need to insert data into a sql table using a csv file with apostrophe(') and ('') in few rows.
I was able to handle it using the below method.
Get open_quote and close_quote and put the username and email_id between these two variable.
SELECT CHR(113)||CHR(39)||CHR(91) INTO OPEN_QUOTE FROM dual;
SELECT CHR(93)||CHR(39) INTO CLOSE_QUOTE FROM dual;
enter image description here
It looks ugly.I could have used replace but i opted for this method.
Could you please let me know of any other method so that my code looks good?
Attached is the screenshot of the dynamic sql.

You can have a single quote in a string by doubling it. For instance:
select 'It''s Bob''s book'
from dual;

As of Oracle 10g in PL/SQL you can have:
V_SQL_STATEMENT := q'[It's Bob's book]';
See Oracle SQL Reference for details on text literals.

Use the alternative-quoting mechanism and several REPLACEs instead of concatenation. It's a little extra work but it makes it clearer what the final SQL statement will look like.
v_sql_statement := replace(replace(replace(replace(
q'[
insert into login
(USER_ID,CLIENT_ID,EMAIL,PSWD_HASH,NETWORK_ID,FAILED_LOGIN_ATTEMPTS,NAME)
VALUES
(
LOGIN_SEQ.nextval,
#P_CLIENT_ID#,
'#PARSE_EMAIL#',
#V_PSWD_HASH#,
NULL,
0,
'#USER_NAME#'
)
]'
, '#P_CLIENT_ID#', p_client_id)
, '#PARSE_EMAIL#', parse_email(lower(c1.email)))
, '#V_PSWD_HASH#', v_pswd_hash)
, '#USER_NAME#', nvl(c1.name, generate_user_name(parse_email(c1.email))))
;

Related

How to execute prepared SQL statement stored in another table

Suppose we have a Teradata table db.queries in which prepared statements are stored in statement_code as CLOB, for example the content of such field can look like:
INSERT INTO DATA.TABLE
(ID, JOB_NAME, DATE)
VALUES(1, 'TEST_JOB', CAST(CURRENT_DAY AS DATE FORMAT 'YYYYMMDD')='$currentDay');
We have a stored procedure, which reads this data and then executes this using the following code:
SELECT statement_code
FROM db.queries
WHERE ACTIVE_FLAG = 1
INTO SQL_QRY;
EXECUTE IMMEDIATE SQL_QRY;
This is failing because the extracted statement_code in the SQL_QRY has now esacped single quotes.
Syntax error, expected something like '')'' or '','' between a string or a Unicode character literal and the word ''YYYYMMDD''.
Returned string from SQL_QRY is:
INSERT INTO DATA.TABLE
(ID, JOB_NAME, DATE)
VALUES(1, ''TEST_JOB'', CAST(CURRENT_DAY AS DATE FORMAT ''YYYYMMDD'')=''$currentDay'');
As opposed to the stored statement_code:
INSERT INTO DATA.TABLE
(ID, JOB_NAME, DATE)
VALUES(1, 'TEST_JOB', CAST(CURRENT_DAY AS DATE FORMAT 'YYYYMMDD')='$currentDay');
We have tried using OREPLACE in the variable setting to no avail. The function can replace double single quotes to any character, but single quotes.
By dumping various testing combinations:
OREPLACE(SQL_QRY, '''''', '*') --replaces to *
OREPLACE(SQL_QRY, '''', '*') --replaces to *
OREPLACE(SQL_QRY, '''', '') --get rids of quotes completely
OREPLACE(SQL_QRY, '''''', '''') --leaves the double quotes
Is there a way to overcome this nuisance or what is the proper way to achieve the goal? Retrieve prepared statements and execute them?
Kind Regards
Since your query is prepared already, I think you don't need to prepare it again, execute immediate converts ' to '' to make a string ready as a SQL statement to be executed and screws your already prepared string up.
So you just need to do :
EXECUTE SQL_QRY;
or if your queries stored with two single quotes maybe you need to convert them to one single quote:
OREPLACE(SQL_QRY, '''', ''')

Syntax for insert data into table in SAP BODS

I tried this to insert data into table in SAP BODS, but it seems like it won't work :
BEGIN
sql('TEST_DB', 'INSERT INTO TEST_CODE VALUES ({$ID_NUMBER}, {$DATE}, {$NAME}))
END
Is there any missing syntax? I already search for the sql statement and followed them, but still can't work. Appreciate any help. Thanks.
SQL function needs two parameters .
1st is the DataStore Name and second being the query. I can't find any flaw in your sql function.May be values are not according to the datatypes of the columns.
Try using SQL transform instead of SQL function
,with SQL transform you can verify the syntax too.
Try the following syntax:
BEGIN
sql('TEST_DB', 'INSERT INTO TEST_CODE VALUES ( ([$ID_NUMBER]), ([$DATE]), ([$NAME]) ))
END
The correct syntax is:
BEGIN
sql('TEST_DB', 'INSERT INTO TEST_CODE VALUES ('|| $ID_NUMBER ||' , '||$DATE|| ' , '||$NAME||')');
END

BLOB to String, SQL Server

I have a text string stored as a BLOB data type in a database. I want to extract it by an SQL select query, but I have problems converting/casting from BLOB to readable text.
I've tried e.g.
select convert(nvarchar(40),convert(varbinary(40),BLOBTextToExtract))
from [NavisionSQL$Customer]
I guess I need something similar, but I can't figure out exactly what I need to do the conversion. Can somebody please give me some directions?
Regards
The accepted answer works for me only for the first 30 characters.
This works for me:
select convert(varchar(max), convert(varbinary(max),myBlobColumn)) FROM table_name
Problem was apparently not the SQL server, but the NAV system that updates the field. There is a compression property that can be used on BLOB fields in NAV, that is not a part of SQL Server. So the custom compression made the data unreadable, though the conversion worked.
The solution was to turn off compression through the Object Designer, Table Designer, Properties for the field (Shift+F4 on the field row).
After that the extraction of data can be made with e.g.:
select convert(varchar(max), cast(BLOBFIELD as binary))
from Table
Thanks for all answers that were correct in many ways!
It depends on how the data was initially put into the column. Try either of these as one should work:
SELECT CONVERT(NVarChar(40), BLOBTextToExtract)
FROM [NavisionSQL$Customer];
Or if it was just varchar...
SELECT CONVERT(VarChar(40), BLOBTextToExtract)
FROM [NavisionSQL$Customer];
I used this script to verify and test on SQL Server 2K8 R2:
DECLARE #blob VarBinary(MAX) = CONVERT(VarBinary(MAX), 'test');
-- show the binary representation
SELECT #blob;
-- this doesn't work
SELECT CONVERT(NVarChar(100), #blob);
-- but this does
SELECT CONVERT(VarChar(100), #blob);
Can you try this:
select convert(nvarchar(max),convert(varbinary(max),blob_column)) from table_name
Found this...
bcp "SELECT top 1 BlobText FROM TableName" queryout "C:\DesinationFolder\FileName.txt" -T -c'
If you need to know about different options of bcp flags...
http://msdn.microsoft.com/en-us/library/ms162802.aspx
CREATE OR REPLACE FUNCTION HASTANE.getXXXXX(p_rowid in rowid) return VARCHAR2
as
l_data long;
begin
select XXXXXX into l_data from XXXXX where rowid = p_rowid;
return substr( l_data, 1, 4000);
end getlabrapor1;

select * from table_name where column like '&nbsp'

I need to find records containing html code such as '&nbsp' But when I try to run the select * from table_name where column like '&nbsp%'
I got prompt asking for the value of nbsp. I guess the database thinks that nbsp is a parameter. I am wondering if the is an escape character so that I can tell the database that "&" is part of my query string. I tryed '\&nbsp' but didn't work.
My environment is Oracle 9i with sqlplus client.
Thanks.
Have a look at this:
SQL Plus FAQ
e.g.
SET ESCAPE '\'
SELECT '\&abc' FROM dual;
Easier way:
SET DEFINE OFF
See:
SET DEFINE
The backslash should work, but I think you need to start your query with
SET ESCAPE ON
In PL/SQL, you would use:
BEGIN select <Column> from <Table_name> into <Variable> where <Column> LIKE '\&nbsp\%' ESCAPE '\'; END
/
Resources:
Wilcards in SQL on PSOUG.org
LIKE Condition in Oracle® Database SQL Language Reference 11g Release 2 (11.2)

SQL Server - Replacing Single Quotes and Using IN

I am passing a comma-delimited list of values into a stored procedure. I need to execute a query to see if the ID of an entity is in the comma-delimited list. Unfortunately, I think I do not understand something.
When I execute the following stored procedure:
exec dbo.myStoredProcedure #myFilter=N'1, 2, 3, 4'
I receive the following error:
"Conversion failed when converting the varchar value '1, 2, 3, 4' to data type int."
My stored procedure is fairly basic. It looks like this:
CREATE PROCEDURE [dbo].[myStoredProcedure]
#myFilter nvarchar(512) = NULL
AS
SET NOCOUNT ON
BEGIN
-- Remove the quote marks so the filter will work with the "IN" statement
SELECT #myFilter = REPLACE(#myFilter, '''', '')
-- Execute the query
SELECT
t.ID,
t.Name
FROM
MyTable t
WHERE
t.ID IN (#myFilter)
ORDER BY
t.Name
END
How do I use a parameter in a SQL statement as described above? Thank you!
You could make function that takes your parameter, slipts it and returns table with all the numbers in it.
If your are working with lists or arrays in SQL Server, I recommend that you read Erland Sommarskogs wonderful stuff:
Arrays and Lists in SQL Server 2005
You need to split the string and dump it into a temp table. Then you join against the temp table.
There are many examples of this, here is one at random.
http://blogs.microsoft.co.il/blogs/itai/archive/2009/02/01/t-sql-split-function.aspx
Absent a split function, something like this:
CREATE PROCEDURE [dbo].[myStoredProcedure]
#myFilter varchar(512) = NULL -- don't use NVARCHAR for a list of INTs
AS
SET NOCOUNT ON
BEGIN
SELECT
t.ID,
t.Name
FROM
MyTable t
WHERE
CHARINDEX(','+CONVERT(VARCHAR,t.ID)+',',#myFilter) > 0
ORDER BY
t.Name
END
Performance will be poor. A table scan every time. Better to use a split function. See: http://www.sommarskog.se/arrays-in-sql.html
I would create a function that takes your comma delimited string and splits it and returns a single column table variable with each value in its own row. Select that column from the returned table in your IN statement.
I found a cute way of doing this - but it smells a bit.
declare #delimitedlist varchar(8000)
set #delimitedlist = '|1|2|33|11|3134|'
select * from mytable where #delimitedlist like '%|' + cast(id as varchar) + '|%'
So... this will return all records with an id equal to 1, 2, 33, 11, or 3134.
EDIT:
I would also add that this is not vulnerable to SQL injection (whereas dynamic SQL relies on your whitelisting/blacklisting techniques to ensure it isn't vulnerable). It might have a performance hit on large sets of data, but it works and it's secure.
I have a couple of blog posts on this as well, with a lot of interesting followup comments and dialog:
More on splitting lists
Processing list of integers