Inserting a string with double quotes into a table - sql

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"');

Related

Find SQL datetimes contained a given list [duplicate]

I am trying to learn the best way to write queries. I also understand the importance of being consistent. Until now, I have randomly used single quotes, double quotes, and backticks without any real thought.
Example:
$query = 'INSERT INTO table (id, col1, col2) VALUES (NULL, val1, val2)';
Also, in the above example, consider that table, col1, val1, etc. may be variables.
What is the standard for this? What do you do?
I've been reading answers to similar questions on here for about 20 minutes, but it seems like there is no definitive answer to this question.
Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword, or when the identifier contains whitespace characters or characters beyond a limited set (see below) It is often recommended to avoid using reserved keywords as column or table identifiers when possible, avoiding the quoting issue.
Single quotes should be used for string values like in the VALUES() list. Double quotes are supported by MySQL for string values as well, but single quotes are more widely accepted by other RDBMS, so it is a good habit to use single quotes instead of double.
MySQL also expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'. Consult the Date and Time Literals documentation for more details, in particular alternatives to using the hyphen - as a segment delimiter in date strings.
So using your example, I would double-quote the PHP string and use single quotes on the values 'val1', 'val2'. NULL is a MySQL keyword, and a special (non)-value, and is therefore unquoted.
None of these table or column identifiers are reserved words or make use of characters requiring quoting, but I've quoted them anyway with backticks (more on this later...).
Functions native to the RDBMS (for example, NOW() in MySQL) should not be quoted, although their arguments are subject to the same string or identifier quoting rules already mentioned.
Backtick (`)
table & column ───────┬─────┬──┬──┬──┬────┬──┬────┬──┬────┬──┬───────┐
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`, `updated`)
VALUES (NULL, 'val1', 'val2', '2001-01-01', NOW())";
↑↑↑↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑↑↑↑↑
Unquoted keyword ─────┴┴┴┘ │ │ │ │ │ │ │││││
Single-quoted (') strings ───────────┴────┴──┴────┘ │ │ │││││
Single-quoted (') DATE ───────────────────────────┴──────────┘ │││││
Unquoted function ─────────────────────────────────────────┴┴┴┴┘
Variable interpolation
The quoting patterns for variables do not change, although if you intend to interpolate the variables directly in a string, it must be double-quoted in PHP. Just make sure that you have properly escaped the variables for use in SQL. (It is recommended to use an API supporting prepared statements instead, as protection against SQL injection).
// Same thing with some variable replacements
// Here, a variable table name $table is backtick-quoted, and variables
// in the VALUES list are single-quoted
$query = "INSERT INTO `$table` (`id`, `col1`, `col2`, `date`) VALUES (NULL, '$val1', '$val2', '$date')";
Prepared statements
When working with prepared statements, consult the documentation to determine whether or not the statement's placeholders must be quoted. The most popular APIs available in PHP, PDO and MySQLi, expect unquoted placeholders, as do most prepared statement APIs in other languages:
// PDO example with named parameters, unquoted
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (:id, :col1, :col2, :date)";
// MySQLi example with ? parameters, unquoted
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (?, ?, ?, ?)";
Characters requring backtick quoting in identifiers:
According to MySQL documentation, you do not need to quote (backtick) identifiers using the following character set:
ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore)
You can use characters beyond that set as table or column identifiers, including whitespace for example, but then you must quote (backtick) them.
Also, although numbers are valid characters for identifiers, identifiers cannot consist solely of numbers. If they do they must be wrapped in backticks.
There are two types of quotes in MySQL:
' for enclosing string literals
` for enclosing identifiers such as table and column names
And then there is " which is a special case. It could be used for one of above-mentioned purposes at a time depending on MySQL server's sql_mode:
By default the " character can be used to enclose string literals just like '
In ANSI_QUOTES mode the " character can be used to enclose identifiers just like `
The following query will produce different results (or errors) depending on SQL mode:
SELECT "column" FROM table WHERE foo = "bar"
ANSI_QUOTES disabled
The query will select the string literal "column" where column foo is equal to string "bar"
ANSI_QUOTES enabled
The query will select the column column where column foo is equal to column bar
When to use what
I suggest that you avoid using " so that your code becomes independent of SQL modes
Always quote identifiers since it is a good practice (quite a few questions on SO discuss this)
(There are good answers above regarding the SQL nature of your question, but this may also be relevant if you are new to PHP.)
Perhaps it is important to mention that PHP handles single and double quoted strings differently...
Single-quoted strings are 'literals' and are pretty much WYSIWYG strings. Double-quoted strings are interpreted by PHP for possible variable-substitution (backticks in PHP are not exactly strings; they execute a command in the shell and return the result).
Examples:
$foo = "bar";
echo 'there is a $foo'; // There is a $foo
echo "there is a $foo"; // There is a bar
echo `ls -l`; // ... a directory list
Backticks are generally used to indicate an identifier and as well be safe from accidentally using the Reserved Keywords.
For example:
Use `database`;
Here the backticks will help the server to understand that the database is in fact the name of the database, not the database identifier.
Same can be done for the table names and field names. This is a very good habit if you wrap your database identifier with backticks.
Check this answer to understand more about backticks.
Now about Double quotes & Single Quotes (Michael has already mentioned that).
But, to define a value you have to use either single or double quotes. Lets see another example.
INSERT INTO `tablename` (`id, `title`) VALUES ( NULL, title1);
Here I have deliberately forgotten to wrap the title1 with quotes. Now the server will take the title1 as a column name (i.e. an identifier). So, to indicate that it's a value you have to use either double or single quotes.
INSERT INTO `tablename` (`id, `title`) VALUES ( NULL, 'title1');
Now, in combination with PHP, double quotes and single quotes make your query writing time much easier. Let's see a modified version of the query in your question.
$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";
Now, using double quotes in the PHP, you will make the variables $val1, and $val2 to use their values thus creating a perfectly valid query. Like
$val1 = "my value 1";
$val2 = "my value 2";
$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";
will make
INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, 'my value 1', 'my value 2')
In MySQL, these symbols are used to delimit a query ` ," ,' and () .
" or ' are used for enclosing string-like values "26-01-2014 00:00:00" or '26-01-2014 00:00:00' . These symbols are only for strings, not aggregate functions like now, sum, or max.
` is used for enclosing table or column names, e.g. select `column_name` from `table_name` where id='2'
( and ) simply enclose parts of a query e.g. select `column_name` from `table_name` where (id='2' and gender='male') or name='rakesh' .
There has been many helpful answers here, generally culminating into two points.
BACKTICKS(`) are used around identifier names.
SINGLE QUOTES(') are used around values.
AND as #MichaelBerkowski said
Backticks are to be used for table and column identifiers, but are
only necessary when the identifier is a MySQL reserved keyword, or
when the identifier contains whitespace characters or characters
beyond a limited set (see below) It is often recommended to avoid
using reserved keywords as column or table identifiers when possible,
avoiding the quoting issue.
There is a case though where an identifier can neither be a reserved keyword or contain whitespace or characters beyond limited set but necessarily require backticks around them.
EXAMPLE
123E10 is a valid identifier name but also a valid INTEGER literal.
[Without going into detail how you would get such an identifier name], Suppose I want to create a temporary table named 123456e6.
No ERROR on backticks.
DB [XXX]> create temporary table `123456e6` (`id` char (8));
Query OK, 0 rows affected (0.03 sec)
ERROR when not using backticks.
DB [XXX]> create temporary table 123451e6 (`id` char (8));
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '123451e6 (`id` char (8))' at line 1
However, 123451a6 is a perfectly fine identifier name (without back ticks).
DB [XXX]> create temporary table 123451a6 (`id` char (8));
Query OK, 0 rows affected (0.03 sec)
This is completely because 1234156e6 is also an exponential number.
The string literals in MySQL and PHP are the same.
A string is a sequence of bytes or characters, enclosed within either
single quote (“'”) or double quote (“"”) characters.
So if your string contains single quotes, then you could use double quotes to quote the string, or if it contains double quotes, then you could use single quotes to quote the string. But if your string contains both single quotes and double quotes, you need to escape the one that used to quote the string.
Mostly, we use single quotes for an SQL string value, so we need to use double quotes for a PHP string.
$query = "INSERT INTO table (id, col1, col2) VALUES (NULL, 'val1', 'val2')";
And you could use a variable in PHP's double-quoted string:
$query = "INSERT INTO table (id, col1, col2) VALUES (NULL, '$val1', '$val2')";
But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)
In combination of PHP and MySQL, double quotes and single quotes make your query-writing time so much easier.
$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";
Now, suppose you are using a direct post variable into the MySQL query then, use it this way:
$query = "INSERT INTO `table` (`id`, `name`, `email`) VALUES (' ".$_POST['id']." ', ' ".$_POST['name']." ', ' ".$_POST['email']." ')";
This is the best practice for using PHP variables into MySQL.
If table cols and values are variables then there are two ways:
With double quotes "" the complete query:
$query = "INSERT INTO $table_name (id, $col1, $col2)
VALUES (NULL, '$val1', '$val2')";
Or
$query = "INSERT INTO ".$table_name." (id, ".$col1.", ".$col2.")
VALUES (NULL, '".$val1."', '".$val2."')";
With single quotes '':
$query = 'INSERT INTO '.$table_name.' (id, '.$col1.', '.$col2.')
VALUES (NULL, '.$val1.', '.$val2.')';
Use back ticks `` when a column/value name is similar to a MySQL reserved keyword.
Note: If you are denoting a column name with a table name then use back ticks like this:
`table_name`. `column_name` <-- Note: exclude . from back ticks.
Single quotes should be used for string values like in the VALUES() list.
Backticks are generally used to indicate an identifier and as well be safe from accidentally using the reserved keywords.
In combination of PHP and MySQL, double quotes and single quotes make your query writing time so much easier.
Besides all of the (well-explained) answers, there hasn't been the following mentioned and I visit this Q&A quite often.
In a nutshell; MySQL thinks you want to do math on its own table/column and interprets hyphens such as "e-mail" as e minus mail.
Disclaimer: So I thought I would add this as an "FYI" type of answer for those who are completely new to working with databases and who may not understand the technical terms described already.
SQL servers and MySQL, PostgreySQL, Oracle don't understand double quotes("). Thus your query should be free from double quotes(") and should only use single quotes(').
Back-trip(`) is optional to use in SQL and is used for table name, db name and column names.
If you are trying to write query in your back-end to call MySQL then you can use double quote(") or single quotes(') to assign query to a variable like:
let query = "select id, name from accounts";
//Or
let query = 'select id, name from accounts';
If ther's a where statement in your query and/or trying to insert a value and/or an update of value which is string use single quote(') for these values like:
let querySelect = "select id, name from accounts where name = 'John'";
let queryUpdate = "update accounts set name = 'John' where id = 8";
let queryInsert = "insert into accounts(name) values('John')";
//Please not that double quotes are only to be used in assigning string to our variable not in the query
//All these below will generate error
let querySelect = 'select id, name from accounts where name = "John"';
let queryUpdate = 'update accounts set name = "John" where id = 8';
let queryInsert = 'insert into accounts(name) values("John")';
//As MySQL or any SQL doesn't understand double quotes("), these all will generate error.
If you want to stay out of this confusion when to use double quotes(") and single quotes('), would recommend to stick with single quotes(') this will include backslash() like:
let query = 'select is, name from accounts where name = \'John\'';
Problem with double(") or single(') quotes arise when we had to assign some value dynamic and perform some string concatenation like:
let query = "select id, name from accounts where name = " + fName + " " + lName;
//This will generate error as it must be like name = 'John Smith' for SQL
//However our statement made it like name = John Smith
//In order to resolve such errors use
let query = "select id, name from accounts where name = '" + fName + " " + lName + "'";
//Or using backslash(\)
let query = 'select id, name from accounts where name = \'' + fName + ' ' + lName + '\'';
If need further clearance do follow quotes in JavaScript
It is sometimes useful to not use quotes... because this can highlight issues in the code generating the query... For example:
Where x and y are should always be integers...
SELECT * FROM table WHERE x= AND y=0
Is a SQL syntax error... a little lazy but can be useful...

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'

How to store a string which has multiple quotes in a database

I want to store a ciphertext in an Oracle database, but I am getting an error:
identifier is too long.
Its probably because there are multiple quotes in the string. So, how do I store such a string?
For example, my ciphertext may look like:
b't\xb2\xb2\xd6\xab\xab[\x8d\xcc\xab\x1dK\xf7\xa4\xf5\x9a\xe5\xc7\xd2\x874\xbf\xb3\xd5\xf0\xc7\xcbL\xb1\x88\xd2\xae\xeeR\xe6\xd9f\xfc\x89\xfb\xc7\xeb\x0e\xca\xbe\x88\x1e\xa8\xcb\x12\x7f\xeaL\xe5o\x01\x0c\x9f\xd1\xfc\xc2Xe\xd9H6\xa4\x02\xde\xa8\xbb\x04\xf6\xa2\x81\xe8\xa4T\x17\xe5\x94\x1a\xd1\xf3\xca\xe8\xc4v\xb2\x94\xe0,\xb8v\x9c\x13m>W6\x1cL\x87\xde\xce-h\xcd"\xa66\xac&\x9b\xc4C\x9eK\x1fL\xff\nW\x06\x06\xc1\xe3\x7f\x1c{\xff\x93\xdb\t\xdb\x13&\x81\x0c\x06\xf1\x81\x99f\n\x7f\x99\x1e\xbd\xd4\x17\xe9\x05\xb7\x97\xf6\x1f\xd5\xb3\xffK/#6A\t\xa2\xba+\xfaxO\xb9\xa7\x86\xac\x10V\xc6\xe0\x96OfF\x9f\xaaM\xe3\xc9\xf6UNO\x15\x8e\r\x00\x07J)lZ\[]N\x181\xa3\xd4\'\x8a\x91\x81\x0c\xe4:\x88\xf8\xbe\xcc\xcc\xa18\xe2.o\xe5\xb4\xd9\xd3Fk\xf9\xff\x9a\xc8\x04\xaa\x9a\xff\xc2q&\xa7\xd2O\x8eh\xd7\xa9\x02\xc5V'
As you can see there is a single and a double quote in this.
So, how do I store such a string?
A simple option is to use the q-quoting mechanism, where you choose something (like a square bracket, curly bracket, ...) that doesn't exist in your string to enclose those values that have multiple single quotes. Otherwise you would have to escape them using double single quotes, but things get tricky once there are consecutive single quotes. It's just too complicated.
So, an example:
SQL> create table test (col varchar2(50));
Table created.
SQL> insert into test values (q'[that's a string and I'm "Little'foot"]');
1 row created.
SQL> select * From test;
COL
--------------------------------------------------
that's a string and I'm "Little'foot"
SQL>
how do I store such a string?
You appear to have binary data and not a "string"; so store it in a data type for binary data such as BLOB:
CREATE TABLE your_table (
ciphertext BLOB
);
Then when you insert it use a parameterised query and bind variables from whatever interface you are using to access the database (from the look of your data, I would guess it is a bytes data type in Python):
For a positional bind variable, you can use the syntax:
INSERT INTO your_table ( ciphertext ) VALUES ( ? );
For a named bind variable, you can use the syntax:
INSERT INTO your_table ( ciphertext ) VALUES ( :your_value );
Then, when you construct your prepared statement to insert the value, you can pass your data in as the bind variable and you do not need to worry about any quotes.

Braces inside the array - postgresql

I have a table "temp" with two attributes: integer, text[].
I would like to insert a record with the brace inside the array.
For example a record like this:
1, {'1{c}1','a'}
where 1 is the integer and '1{c}1' is the first element of the array and 'a' the second element of the array.
I tried a simply insert like this:
INSERT INTO temp VALUES (id, '{'1{c}1','a'}');
but it says that is malformed.
As an addition, it's also possible to use array constructors, I think it's more safe to use, because array elements are just SQL constants and you also could use expressions inside the array constructors:
insert into "temp" values(1, array['1{c}1','a']);
it's clear that this is array of strings, and this too
insert into "temp" values(1, array['1','2']);
According to the PostgreSQL documentation for arrays,
You can put double quotes around any element value, and must do so if it contains commas or curly braces.
A correct syntax would like this:
INSERT INTO "temp" VALUES (1, '{"1{c}1",a}');
You can see a complete, working example on SQL fiddle.
You don't want those inner single quotes.
INSERT INTO temp VALUES (id, '{1{c}1,a}');

SQL INSERT Query with String variable in it

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.