SQL INSERT Query with String variable in it - sql

I have an SQL query in which I need to insert a string variable but I am getting errors from it.
Below is my SQL INSERT query:
Insert into User(Employee, Name, Address, Role, Action)
Select distinct ur1.Employee, ur1.Name, ur1.Address, ur1.Role, ['%" + action + "%'] as [Action] FROM UserRoles ur1)";
string action="insert delete query in database"
I would like to insert string action into my INSERT statement, but I am getting lots of syntax errors.
Can anyone help me with the query?
Thank you in advance for any help.

The SQL operator for string concatenation is ||.

Insert into User(Employee, Name, Address, Role, Action)
Select distinct ur1.Employee, ur1.Name, ur1.Address, ur1.Role,'insert delete query in database'
FROM UserRoles ur1;

You should try
INSERT INTO User (Employee, Name, Address, Role, Action)
SELECT DISTINCT ur1.Employee, ur1.Name,
ur1.Address, ur1.Role,
['%insert delete query in database%']
FROM UserRoles ur1

The part where you are concatenating your action variable to the rest of the script looks something like this after the concatenation:
…
['the string value goes here'] as [Action]
…
I'm now going to take a wild guess but it does seem as if you are on SQL Server or on Sybase, because of the square brackets. Now, in either of those two products, the sequences of characters enclosed in square brackets would be considered delimited identifiers. Using the brackets in your example does make sense for [Action] but seems absolutely pointless for the ['...'] part of your script. It is more likely that you meant simply '...', i.e. without the square brackets, which simply stands for a string constant.
One other thing to note: there's an unmatched closing parenthesis at the end of your SQL statement.

Related

How can I use ' this symbol in SQL [duplicate]

What is the correct SQL syntax to insert a value with an apostrophe in it?
Insert into Person
(First, Last)
Values
'Joe',
'O'Brien'
I keep getting an error as I think the apostrophe after the O is the ending tag for the value.
Escape the apostrophe (i.e. double-up the single quote character) in your SQL:
INSERT INTO Person
(First, Last)
VALUES
('Joe', 'O''Brien')
/\
right here
The same applies to SELECT queries:
SELECT First, Last FROM Person WHERE Last = 'O''Brien'
The apostrophe, or single quote, is a special character in SQL that specifies the beginning and end of string data. This means that to use it as part of your literal string data you need to escape the special character. With a single quote this is typically accomplished by doubling your quote. (Two single quote characters, not double-quote instead of a single quote.)
Note: You should only ever worry about this issue when you manually edit data via a raw SQL interface since writing queries outside of development and testing should be a rare occurrence. In code there are techniques and frameworks (depending on your stack) that take care of escaping special characters, SQL injection, etc.
You just have to double up on the single quotes...
insert into Person (First, Last)
values ('Joe', 'O''Brien')
You need to escape the apostrophe. In T-SQL this is with a double apostrophe, so your insert statement becomes:
Insert into Person
(First, Last)
Values
'Joe', 'O''Brien'
Because a single quote is used for indicating the start and end of a string; you need to escape it.
The short answer is to use two single quotes - '' - in order for an SQL database to store the value as '.
Look at using REPLACE to sanitize incoming values:
Oracle REPLACE
SQL Server REPLACE
MySQL REPLACE
PostgreSQL REPLACE
You want to check for '''', and replace them if they exist in the string with '''''' in order to escape the lone single quote.
Single quotes are escaped by doubling them up,
The following SQL illustrates this functionality.
declare #person TABLE (
[First] nvarchar(200),
[Last] nvarchar(200)
)
insert into #person
(First, Last)
values
('Joe', 'O''Brien')
select * from #person
Results
First | Last
===================
Joe | O'Brien
eduffy had a good idea. He just got it backwards in his code example. Either in JavaScript or in SQLite you can replace the apostrophe with the accent symbol.
He (accidentally I am sure) placed the accent symbol as the delimiter for the string instead of replacing the apostrophe in O'Brian. This is in fact a terrifically simple solution for most cases.
The apostrophe character can be inserted by calling the CHAR function with the apostrophe's ASCII table lookup value, 39. The string values can then be concatenated together with a concatenate operator.
Insert into Person
(First, Last)
Values
'Joe',
concat('O',char(39),'Brien')
use double quotation marks around the values.
insert into Person (First, Last) Values("Joe","O'Brien")
Another way of escaping the apostrophe is to write a string literal:
insert into Person (First, Last) values (q'[Joe]', q'[O'Brien]')
This is a better approach, because:
Imagine you have an Excel list with 1000's of names you want to upload to your database. You may simply create a formula to generate 1000's of INSERT statements with your cell contents instead of looking manually for apostrophes.
It works for other escape characters too. For example loading a Regex pattern value, i.e. ^( *)(P|N)?( *)|( *)((<|>)\d\d?)?( *)|( )(((?i)(in|not in)(?-i) ?(('[^']+')(, ?'[^']+'))))?( *)$ into a table.
If it is static text, you can use two single quote instead of one as below:
DEC #text = 'Khabir''s Account'
See after Khabir there are two single quote ('')
If your text is not static and it is passed in Store procedure parameter then
REPLACE(#text, '''', '')
This is how my data as API response looks like, which I want to store in the MYSQL database. It contains Quotes, HTML Code , etc.
Example:-
{
rewardName: "Cabela's eGiftCard $25.00",
shortDescription: '<p>adidas gift cards can be redeemed in over 150 adidas Sport Performance, adidas Originals, or adidas Outlet stores in the US, as well as online at adidas.com.</p>
terms: '<p>adidas Gift Cards may be redeemed for merchandise on adidas.com and in adidas Sport Performance, adidas Originals, and adidas Outlet stores in the United States.'
}
SOLUTION
CREATE TABLE `brand` (
`reward_name` varchar(2048),
`short_description` varchar(2048),
`terms` varchar(2048),
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
While inserting , In followed JSON.stringify()
let brandDetails= {
rewardName: JSON.stringify(obj.rewardName),
shortDescription: JSON.stringify(obj.shortDescription),
term: JSON.stringify(obj.term),
}
Above is the JSON object and below is the SQL Query that insert data into MySQL.
let query = `INSERT INTO brand (reward_name, short_description, terms)
VALUES (${brandDetails.rewardName},
(${brandDetails.shortDescription}, ${brandDetails.terms})`;
Its worked....
Use a backtick (on the ~ key) instead;
`O'Brien`
the solution provided is not working fine, since it ads the string with two single quote in database, the simplest way is to use anti back slash before the apostrophe (single quote).
Insert into Person (First, Last) Values 'Joe', 'O\'Brien'

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'.

SQL Replace comma in results without using replace

I feel like this should be simple enough to do, but have not found any solutions that didn't use replace so far. I have the following select statement I am running, and for some of the columns there are commas separating the values. I would like to replace these commas with semicolons, however I only want to do it in the select statement. I don't want it to alter the values in the tables at all. This is not a one off statement either, or I'd just replace all the commas with semicolons and then revert back.
SELECT a.Category_Id, a.Category_Name, ISNULL(b.Category_Alias, '') as Category_Alias,
ISNULL(b.SUPPORT_NAMES, '') as SUPPORT_NAMES
FROM Categories a
INNER JOIN CategoryInfo b on b.Category_Id=a.Category_Id
For the Category_Alias column, the records are actually stored like CS, Customer Support and I want that to show up as CS; Customer Support just for the select statement.
I believe you may be confused as to what the REPLACE function is doing. You can use REPLACE within your SELECT statement without altering the data in the database:
SELECT REPLACE(MyField, ',', ';') AS NewFieldName
FROM MyTable
I believe you don't want to replace the value physically in the table, but ok to replace on select
So you can
Select REPLACE(ColumnName,',',';')
From TableName
Most SQL servers implement an inline replace function. Most of them are named replace(), and can also be used in a select statement.
Example from MySQL:
SELECT field, REPLACE(field,',',';') FROM my_table;

Inserting a string with double quotes into a table

I'm using Oracle 10g and I'm having a problem inserting a string with double quotes into a table. This is my statement
INSERT INTO USERS (ID, NAME, USERNAME) VALUES (NULL, "tes", "hello");
The query above fails with the error "Oracle column not allowed here".
If I change double quotes to single quotes, as below the statement is successful.
INSERT INTO USERS (ID, NAME, USERNAME) VALUES (NULL, 'tes', 'hello');
But, I want to insert the double quotes into the table.
Is it possible to have double quote in strings in an insert statement? I don't want to use REPLACE() because my query is automatically generated from an array.
A double quote is used to denote a quoted identifier, i.e. an object name that does not solely consist of alpha-numeric characters, $ and #. As an aside, it's recommended that you do not use quoted identifiers. This is the reason for your original ORA-00984 error. Oracle is assuming that "tes" is a column, not a string, and you can't use a column name in the VALUES clause of an INSERT statement, as explained in the error message.
In order to insert the string "tes" into a table you need to ensure that it is quoted correctly:
Character literals are enclosed in single quotation marks so that the database can distinguish them from schema object names.
Any character can be part of a string so in order to insert a double quote into a table you need to enclose it within single quotes.
insert into users (id, name, username)
values (null, '"tes"', '"hello"');
Here's a SQL Fiddle to demonstrate.
One additional thing to note. You state that this query is automatically generated, which means you may be vulnerable to SQL injection. I would highly recommend reading about bind variables in Guarding Against SQL Injection.
It is possible. In Oracle, you quote string literals using single quotes.
If you want to insert test into the database then you must quote that as 'test'.
INSERT INTO USERS (NAME) VALUES ('test');
If you want to insert "test" into the database then you must quote that as '"test"'.
INSERT INTO USERS (NAME) VALUES ('"test"');
Try wrapping the values inside single quotes.
INSERT INTO USERS (ID, NAME, USERNAME) VALUES (NULL, '"tes"', '"hello"');

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;