getting error on while inserting a single quotation values - sql

Table1
EmpName1
Raja
Rav'i
Ramu'i
Rajes'ih
Table2
EmpName2
....
When I inserting table2.empname2 from table1.empname1, It inserted only the raja, remaining rows were not inserted it showing error in '(single quotation)
"Showing error as incorrect syntax near rav"
vb6 code.
INSERT INTO table2 (EmpName) VALUES('" & EmpName & "')
How can I insert a name with a single quotation also?

You can either escape your single quotation with something like
empName = replace(empName, "'", "''")
or paramertize your query...

It is highly recommended to use a parametrized query (see e.g. this article), instead of building your SQL query as a string. This protects you from many forms of SQL injection, and is also often faster.
Or directly use some kind of persistence framework, if you have a lot of DB interaction.
Your query will not work because in string SQL queries, the ' must be escaped (as ''). And BTW, if you want to insert values from one table into another, it is usually not a good idea to do a SELECT, then an INSERT in a loop, like you do. Just do a
INSERT INTO table2 SELECT ... FROM table1

Related

Regular Expression in SQL statement

I'm new in regular expression, and would like to ask help with the problem I have. I had a form, and it has drop down field where user can select one or more values, so the value for that drop down can be Faculty of Arts (if user chose one option) or Faculty of Arts, Faculty of Medicine (if user chose these two from the drop down).
Now, I want to convert this value, so that I can use it to filter my query. I will use this / these value(s) in WHERE clause. In this case, I have to reformat this value to "Faculty of Arts", "Faculty of Medicine", so it will fit in this statement:
SELECT * FROM myTable WHERE t_faculty IN ("Faculty of Arts", "Faculty of Medicine")
A friend of mine suggested me to try regular expression embedded in this SQL statement (I'm using SQL Server for the database). Do you have any idea on how to parse, and embed it in the SQL statement? Basically I need to add " characters in the beginning and end of the string, and replace the ,[space] with ",[space]" to get the wanted result.
Thank you!
Agus
You can split a comma-delimited string within SQL using STRING_SPLIT.
select * from myTable
where t_faculty in (
select value from string_split('Faculty of Arts, Faculty of Medicine', ',')
)
STRING_SPLIT returns a table of string values that are separated by the delimiter in the input string.
Otherwise you can use several pattern matching functions:
LIKE
PATINDEX
An SQL CLR (e.g.: C#) function that does expression matching. See SQL Server Regex.
You may also choose to simply split the string in your app. Then build the appropriate SQL command (or use something like Contains in linq).
You are not clear how you are passing those strings to SQL Server.
And SQL Server delimits strings with single quotes, i.e apostrophes not double quotes.
In whatever client-side code you have access to, simply concatenate the selected strings with apostrophes.
So if a user picks Faculty of Arts and Faculty of Medicine then you can join it all into one long string like
"'" & <selected option> & "'" & ",'" & <selected option> & "'"
You don't use regular expressions here to change the highlighted part of your SQL code :
SELECT FROM myTable WHERE t_faculty IN **("Faculty of Arts", "Faculty of Medicine")
I think your understanding about the way we use Regular Expressions could be wrong. You generally use regular expressions when you are trying to match with strings in your database which share some common properties. For instance if you have two rows with the fields "Faculty of Arts 1" and "Faculty of Arts 2". And you are trying to look up all the rows which have "Faculty of Arts" in general, then you could write it as SELECT * FROM myTABLE WHERE t_faculty LIKE 'Faculty of Arts*' where * would match anything after the text.
Instead of t_faculty IN (value1,value2), you will write something like t_faculty LIKE 'your regular_expression here'.

String Literal Escaping and Database

I have been reading up on escaping strings to avoid SQL Injection. I do understand that parameterized queries are the safest way to avoid Injection.
But i do have a question regarding Escaping as means of complimenting Parameterized queries.
Suppose the input field "Name" had the value O'Brian and was escaped using the below routine:
sSanitizedInput = "'" & Replace(sInput, "'", "''") & "'"
So the value now looks like O''Brian. If this were to be inserted in the database using the Insert query, will the inserted value be actually O''BRIAN?
If that is the case, then in order to search the name column for the inserted value O''Brian, will i have to escape it to O''Brian before executing the Select query to match it with the value inserted in the DB?

Insert statement in sql with one field set as autonumber

I am having three columns in my table branch i.e id(Autonumber),code(text),desc(text).I am trying to execute this sql
insert into branch(code,desc) values('"+b+"','"+c+"')";
which gives me error syntax error..please help
One of your columns has name DESC, which is Reserved Keyword. In order to peoperly execute the INSERT statement, you need to delimite the column by using brackets eg
insert into branch(code,[desc]) values ('"+b+"','"+c+"')";
MSACCESS Reserved Keywords List
One more thing, your code is prone to SQL Injection. Please do parameterized the query.

How can I store sql statements in an oracle table?

We need to store a select statement in a table
select * from table where col = 'col'
But the single quotes messes the insert statement up.
Is it possible to do this somehow?
From Oracle 10G on there is an alternative to doubling up the single quotes:
insert into mytable (mycol) values (q'"select * from table where col = 'col'"');
I used a double-quote character ("), but you can specify a different one e.g.:
insert into mytable (mycol) values (q'#select * from table where col = 'col'#');
The syntax of the literal is:
q'<special character><your string><special character>'
It isn't obviously more readable in a small example like this, but it pays off with large quantities of text e.g.
insert into mytable (mycol) values (
q'"select empno, ename, 'Hello' message
from emp
where job = 'Manager'
and name like 'K%'"'
);
How are you performing the insert? If you are using any sort of provider on the front end, then it should format the string for you so that quotes aren't an issue.
Basically, create a parameterized query and assign the value of the SQL statement to the parameter class instance, and let the db layer take care of it for you.
you can either use two quotes '' to represent a single quote ' or (with 10g+) you can also use a new notation:
SQL> select ' ''foo'' ' txt from dual;
TXT
-------
'foo'
SQL> select q'$ 'bar' $' txt from dual;
TXT
-------
'bar'
If you are using a programming language such as JAVA or C#, you can use prepared (parametrized) statements to put your values in and retrieve them.
If you are in SQLPlus you can escape the apostrophe like this:
insert into my_sql_table (sql_command)
values ('select * from table where col = ''col''');
Single quotes are escaped by duplicating them:
INSERT INTO foo (sql) VALUES ('select * from table where col = ''col''')
However, most database libraries provide bind parameters so you don't need to care about these details:
INSERT INTO foo (sql) VALUES (:sql)
... and then you assign a value to :sql.
Don't store SQL statements in a database!!
Store SQL Views in a database. Put them in a schema if you have to make them cleaner. There is nothing good that will happen ever if you store SQL Statements in a database, short of logging this is categorically a bad idea.
Also if you're using 10g, and you must do this: do it right! Per the FAQ
Use the 10g Quoting mechanism:
Syntax
q'[QUOTE_CHAR]Text[QUOTE_CHAR]'
Make sure that the QUOTE_CHAR doesnt exist in the text.
SELECT q'{This is Orafaq's 'quoted' text field}' FROM DUAL;

SQL: Use the same string for both INSERT and UPDATE?

The INSERT syntax I've been using is this
INSERT INTO TableName VALUES (...)
The UPDATE syntax I've been using is
UPDATE TableName SET ColumnName=Value WHERE ...
So in all my code, I have to generate 2 strings, which would result in something like this
insertStr = "(27, 'John Brown', 102)";
updateStr = "ID=27, Name='John Brown', ItemID=102";
and then use them separately
"UPDATE TableName SET " + updateStr + " WHERE ID=27 " +
"IF ##ROWCOUNT=0 "+
"INSERT INTO TableName VALUES (" + insertStr + ")"
It starts bothering me when I am working with tables with like 30 columns.
Can't we generate just one string to use on both INSERT and UPDATE?
eg. using insertStr above on UPDATE statement or updateStr on INSERT statement, or a whole new way?
I think you need a whole new approach. You are open to SQL Injection. Provide us with some sample code as to how you are getting your data inputs and sending the statements to the database.
alt text http://goose.ycp.edu/~weddins/440/S09%20IFS440%20Bobby%20Drop%20Tables.PNG
As far as I'm aware, what you're describing isn't possible in ANSI SQL, or any extension of it that I know. However, I'm mostly familiar with MySQL, and it likely depends completely upon what RDBMS you're using. For example, MySQL has "INSERT ... ON DUPLICATE KEY UPDATE ... " syntax, which is similar to what you've posted there, and combines an INSERT query with an UPDATE query. The upside is that you are combining two possible operations into a single query, however, the INSERT and UPDATE portions of the query are admittedly different.
Generally, this kind of thing can be abstracted away with an ORM layer in your application. As far as raw SQL goes, I'd be interested in any syntax that worked the way you describe.
Some DBMS' have an extension to do this but why don't you just provide a function to do it for you? We've actually done this before.
I'm not sure what language you're using but it's probably got associative arrays where you can wrote something like:
pk{"ID"} = "27"
val{"Name"} = "'John Brown'"
val{"ItemID"} = "102"
upsert ("MyTable", pk, val)
and, if it doesn't have associative arrays, you can emulate them with multiple integer-based arrays of strings.
In our upsert() function, we just constructed a string (update, then insert if the update failed) and passed it to our DBMS. We kept the primary keys separate from our other fields since that made construction of the update statement a lot easier (primary key columns went in the where clause, other columns were just set).
The result of the calls above would result in the following SQL (we had a different check for failed update but I've put your ##rowcount in for this example):
update MyTable set
Name = 'John Brown',
ItemID = 102
where ID = 27
if ##rowcount=0
insert into MyTable (ID, Name, ItemID) values (
27,
'John Brown',
102
)
That's one solution which worked well for us. No doubt there are others.
Well, how about no statements? You might want to look into an ORM to handle this for you...
Some databases have proprietary extensions that do exactly this.
I agree that the syntax of INSERT and UPDATE could be more consistent, but this is just a fact of life now -- it ain't gonna change now. For many scenarios, the best option is your "whole new way": use an object-relational mapping library (or even a weak-tea layer like .NET DataSets) to abstract away the differences, and stop worrying about the low-level SQL syntax. Not a viable option for every application, of course, but it would allow you to just construct or update an object, call a Save method and have the library figure out the SQL syntax for you.
If you think about it, INSERT and UPDATE are exactly the same thing. They map field names to values, except the UPDATE has a filter.
By creating an associative array, where the key is the field name and the value is the value you want to assign to the field, you have your mapping. You just need to convert it to a the proper string format depending on INSERT or UPDATE.
You just need to create a function that will handle the conversion based on the parameters given.
SQL Server 2008:
MERGE dbo.MyTable AS T
USING
(SELECT
#mykey AS MyKey
#myval AS MyVal
) AS S
ON (T.MyKey = S.MyKey)
WHEN MATCHED THEN
UPDATE SET
T.MyVal = S.MyVal
WHEN NOT MATCHED THEN
INSERT (MyKey, MyVal)
VALUES (S.MyKey, S.MyVal)
MySQL:
INSERT (MyKey, MyVal)
INTO MyTable
VALUES({$myKey}, {$myVal})
ON DUPLICATE KEY UPDATE myVal = {$myVal}