I have requirement for the filter the names in the table.
Example Table Name :- student
Columns :- Name, Class.
The date is like
Name ----Class
HIGHSPEED ---C
HIGHSPEED11 ---C1
HIGHSPEED22 ---C2
NORMAL-------------N
NORMAL1-------------N1
NORMAL2-------------N2
Like this i have data SRQ, PWE ...
My requirement is I need to remove some data using a name...
SELECT distinct name FROM student WHERE UPPER (name) LIKE 'SRP%'
Or UPPER (name) LIKE 'HIGHSPEED%'
Or UPPER (name) LIKE 'SRQ%'
Or UPPER (name) LIKE 'PWE%'
Or UPPER (name) LIKE 'SPINTERFACE%'
Or UPPER (name) LIKE 'SRM%'
Instead of using OR condition, please let me know any other option... ?
I'm not an Oracle user, but a quick look through their docs indicates Oracle supports POSIX Extended Regular Expressions (ERE). So a regular expression that matches the names in your query would be:
^(SRP|HIGHSPEED|SRQ|PWE|SPINTERFACE|SRM)
It looks like Oracle supplies a REGEXP_LIKE function, so your query could be re-written using the regular expression as:
SELECT distinct name FROM student WHERE REGEXP_LIKE(UPPER(name), '^(SRP|HIGHSPEED|SRQ|PWE|SPINTERFACE|SRM)');
I'm afraid I don't have access to Oracle to test but that's what the regular expression will look like.
Related
One of my columns is called from. I can't change the name because I didn't make it.
Am I allowed to do something like SELECT from FROM TableName or is there a special syntax to avoid the SQL Server being confused?
Wrap the column name in brackets like so, from becomes [from].
select [from] from table;
It is also possible to use the following (useful when querying multiple tables):
select table.[from] from table;
If it had been in PostgreSQL, use double quotes around the name, like:
select "from" from "table";
Note: Internally PostgreSQL automatically converts all unquoted commands and parameters to lower case. That have the effect that commands and identifiers aren't case sensitive. sEleCt * from tAblE; is interpreted as select * from table;. However, parameters inside double quotes are used as is, and therefore ARE case sensitive: select * from "table"; and select * from "Table"; gets the result from two different tables.
These are the two ways to do it:
Use back quote as here:
SELECT `from` FROM TableName
You can mention with table name as:
SELECT TableName.from FROM TableName
While you are doing it - alias it as something else (or better yet, use a view or an SP and deprecate the old direct access method).
SELECT [from] AS TransferFrom -- Or something else more suitable
FROM TableName
Your question seems to be well answered here, but I just want to add one more comment to this subject.
Those designing the database should be well aware of the reserved keywords and avoid using them. If you discover someone using it, inform them about it (in a polite way). The keyword here is reserved word.
More information:
"Reserved keywords should not be used
as object names. Databases upgraded
from earlier versions of SQL Server
may contain identifiers that include
words not reserved in the earlier
version, but that are reserved words
for the current version of SQL Server.
You can refer to the object by using
delimited identifiers until the name
can be changed."
http://msdn.microsoft.com/en-us/library/ms176027.aspx
and
"If your database does contain names
that match reserved keywords, you must
use delimited identifiers when you
refer to those objects. For more
information, see Identifiers (DMX)."
http://msdn.microsoft.com/en-us/library/ms132178.aspx
In Apache Drill, use backquotes:
select `from` from table;
If you ARE using SQL Server, you can just simply wrap the square brackets around the column or table name.
select [select]
from [table]
I have also faced this issue.
And the solution for this is to put [Column_Name] like this in the query.
string query= "Select [Name],[Email] from Person";
So it will work perfectly well.
Hi I work on Teradata systems that is completely ANSI compliant. Use double quotes " " to name such columns.
E.g. type is a SQL reserved keyword, and when used within quotes, type is treated as a user specified name.
See below code example:
CREATE TABLE alpha1
AS
(
SEL
product1
type_of_product AS "type"
FROM beta1
) WITH DATA
PRIMARY INDEX (product1)
--type is a SQL reserved keyword
TYPE
--see? now to retrieve the column you would use:
SEL "type" FROM alpha1
I ran in the same issue when trying to update a column which name was a keyword. The solution above didn't help me. I solved it out by simply specifying the name of the table like this:
UPDATE `survey`
SET survey.values='yes,no'
WHERE (question='Did you agree?')
The following will work perfectly:
SELECT DISTINCT table.from AS a FROM table
Some solid answers—but the most-upvoted one is parochial, only dealing with SQL Server. In summary:
If you have source control, the best solution is to stick to the rules, and avoid using reserved words. This list has been around for ages, and covers most of the peculiarities. One tip is that reserved words are rarely plural—so you're usually safe using plural names. Exceptions are DIAGNOSTICS, SCHEMAS, OCTETS, OFFSETS, OPTIONS, VALUES, PARAMETERS, PRIVILEGES and also verb-like words that also appear plural: OVERLAPS, READS, RETURNS, TRANSFORMS.
Many of us don't have the luxury of changing the field names. There, you'll need to know the details of the RDBM you're accessing:
For SQL Server use [square_braces] around the name. This works in an ODBC connection too.
For MySQL use `back_ticks`.
Postgres, Oracle and several other RDBMs will apparently allow "double_quotes" to be used.
Dotting the offending word onto the table name may also work.
You can put your column name in bracket like:
Select [from] from < ur_tablename>
Or
Put in a temprary table then use as you like.
Example:
Declare #temp_table table(temp_from varchar(max))
Insert into #temp_table
Select * from your_tablename
Here I just assume that your_tablename contains only one column (i.e. from).
In MySQL, alternatively to using back quotes (`), you can use the UI to alter column names. Right click the table > Alter table > Edit the column name that contains sql keyword > Commit.
select [from] from <table>
As a note, the above does not work in MySQL
Judging from the answers here and my own experience. The only acceptable answer, if you're planning on being portable is don't use SQL keywords for table, column, or other names.
All these answers work in the various databases but apparently a lot don't support the ANSI solution.
Simple solution
Lets say the column name is from ; So the column name in query can be referred by table alias
Select * from user u where u.from="US"
In Oracle SQL Developer, pl/sql you can do this with double quotes but if you use double quotes you must type the column names in upper case. For example, SELECT "FROM" FROM MY_TABLE
Here is the code:
-- create table novaya.unnormal as
select query from default.daily_session_mobile
where dt = '20161020'
and page in ('/click_search_deal', '/click_search_product')
and query like '%memberID=33930938%'
and query like '%스텐드지퍼팩%'
The result only has one record and it is right
The value in the field of "query" is
searchCount=52&rank=39&logType=click¤tView=/search_list&searchId=4c3ecee1354943e999e0c1566243bf87&logCategory=event&itemID=22780015&itemProductID=4&q=스텐드지퍼팩&memberID=33930938&productID=4993730&eventReferrer=/click_search_list&request_time=1476889555129&tz=+0900&appVersion=4.3.8&wl_mo=LG-F400L&wl_ma=LGE&wl_sn=Android&wl_v=4.4.2&wl_r=1440x2392&wl_l=ko&wl_c=KR
and there is no space in the value. We focus on the "q=스텐드지퍼팩&" in it.
It seems good.
But when I use create table novaya.unnormal as select ...
the table novaya.unnormal's query have been cut.
The new "query" only has a part of the whole query which is
"searchCount=52&rank=39&logType=click¤tView=/search_list&searchId=4c3ecee1354943e999e0c1566243bf87&logCategory=event&itemID=22780015&itemProductID=4&q="
half of it is missing.
What is wrong with this?
When you create a table using create table novaya.unnormal as statement, without specifying any input/output format and delimiters, all defaults will be chosen which probably causes the 스 character to act as a separator.
I suggest looking at the properties of the source table (describe formatted default.daily_session_mobile), and creating the new table with similar input/output format and delimiters. (setting them between novaya.unnormal and as)
I am transfering from access to oracle and couldn't find a roughly equals function in oracle. Does such a thing exist?
I am referring to something like:
SELECT * FROM Table WHERE name ='*nswer is thi*';
Use LIKE:
SELECT * FROM Table WHERE name LIKE '%nswer is thi%';
Explanation:
This query will select records which contains "nswer is thi" anywhere in the field name.
For example:
name
--------------------
answer is this
blahnswer is thiblah
The LIKE conditions specify a test involving pattern matching. Whereas the equality operator (=) exactly matches one character value to another
Read more here.
I have a database containing user details. I don't have separate columns for 'firstname' and 'lastname'. I have used only a single column: 'name'. My query is like this:
ps_details=con.prepareStatement("select * from student_details where name=?");
ps_details.setString(1,name);
The problem is:
In db the name is stored in UPPERCASE. So when the user types his/her name in lowercase or mixed-case, the search is unsuccessful. What is the efficient solution for this problem?
Further, what if 'name' are stored in db in lower-case, mixed-case as well as uppercase, i.e., if the case is not known before hand. I also want to use like clause
I am using Oracle 11g Express Editon.
If you really intend to do an exact match (i.e. the user needs to enter their entire name in order to do the search rather than just entering a portion of their name), you can wrap both sides of the expression in either the UPPER or the LOWER function.
SELECT *
FROM student_details
WHERE upper(name) = upper(?)
If you do that, however, Oracle won't be able to use an index on name so it will have to scan the entire table. That's not particularly efficient. You can address that issue by creating a function based index on upper(name)
CREATE INDEX idx_upper_name
ON student_details( upper(name) );
In reality, though, I suspect that you don't want to do a wild-card based match. You almost certainly want to allow the user to enter some part of the name and to return the results that contain that string. So if I were a student, you probably want to allow the user to search for either 'Justin' or 'Cave' or 'Justin Cave' or 'Just' and have all those searches return my row (along with whatever other rows match, of course). If you want to do that, the simplest approach would be to use the LIKE function along with the % wildcard
SELECT *
FROM student_details
WHERE upper(name) like '%' || upper(?) || '%'
will return all the rows where the input string is found anywhere in the text you're searching. But that realistically takes us back to nearly square one with respect to performance-- having the leading wildcard is going to make it very difficult for Oracle to benefit from using the index we defined on UPPER(name). This is why most people would store first and last name separately. That allows them to do something like
SELECT *
FROM student_details
WHERE upper(first_name) like upper(?) || '%'
OR upper(last_name) like upper(?) || '%'
This allows them to return my row whether the user searches for 'Justin' or 'Cave' or 'Just' and regardless of the casing of the data in the database or the data that is entered in the search. And it is able to use appropriate function-based indexes on the data.
UPPER - the upper function converts all letters in the specified string to uppercase. Use it on both the variable (user input) and table column values, convert them both to the same case for comparison to handle both problems. (You could also use lower - the idea is to convert both to the same case for comparison). *EDITED FOR LIKE with only the postceding wildcard *
select * from student_details where UPPER(name) like UPPER(?) || '%'
This you have to play with, but I think you can also do the following with the wildcard.
ps_details=con.prepareStatement("select * from student_details where UPPER(name) like UPPER(?)");
ps_details.setString(1,name%);
Try using UPPER() on your input.
I am using oracleclient provider. I was wondering how do I use a parameter in the query.
select * from table A where A.a in ( parameter).
The parameter should be a multivalue parameter.
how do I create a data set?
Simple. Add the parameter to the report and make sure to check it off as multi-valued. Then in the data tab and go in and edit the query click the "..." button to edit the dataset. Under the parameters tab create a mapping parameter so it looks something like this (obviously you will have different names for your parameters):
#ids | =Parameters!ContractorIDS.Value
Then in the query tab use the coorelated sub-query like your example above. I have done this many times with SQL server and there is no reason it should not work with Oracle since SSRS is going to build an ANSI compliant SQL statement which it will pass to Oracle.
where A.myfield in (#ids)
You can't have a variable in list in oracle directly. You can however, break apart a comma seperated list into rows that can be used in your subquery. The string txt can be replaced by any number of values seperated by a comma.
select * from a where a.a in (
SELECT regexp_substr(txt,'[^,]+',1,level)
FROM (SELECT 'hello,world,hi,there' txt -- replace with parameter
FROM DUAL)
CONNECT BY LEVEL <= LENGTH (REGEXP_REPLACE (txt, '[^,]'))+1
)
The query works by first counting the number of commas that are in the text string. It does this by using a reqular expression to remove all non commas and then counts the length of the remainder.
It then uses an Oracle "trick" to return that number + 1 number of rows from the dual table. It then uses the regexp_substr function to pull out each occurence.
Firstly in SSRS with an Oracle OLEDB connection you need to use the colon, not the # symbol e.g. :parameter not #parameter but then you aren't able to do this as a multi-valued parameter, it only accepts single values. Worse, if you are using an ODBC connection you have to use the question mark by itself e.g. ? not #parameter and then the ordering of parameters becomes important, and they also cannot be multi-valued. The only ways you are left with is using an expression to construct a query (join() function for the param) or calling a stored proc.
The stored proc option is best because the SSRS can handle the parameters for stored procs to both SQL Server and Oracle very cleanly, but if that is not an option you can use this expression:
="select column1, column2, a from table A where A.a in (" + Join(Parameters!parameter.Value,", ") + ")"
Or if the parameter values are strings which need apostrophes around them:
="select column1, column2, a from table A where A.a in ('" + Join(Parameters!parameter.Value,"', '") + "')"
When you right-click on the dataset, you can select "dataset properties" and then use the fx button to edit the query as an expression, rather than using the query designer which won't let you edit it as an expression.
This expression method is limited to a maximum limit of about 1000 values but if you have that many this is the wrong way to do it anyway, you'd rather join to a table.
I don't think you can use a parameter in such a situation.
(Unless oracle and the language you're using supports array-type parameters ? )
The parameters in oracle are defined as ":parametername", so in your query you should use something like:
select * from table A where value in (:parametername)
Add the parameter to the paramaters folders in the report and mark the checkbox "Allow multiple values".
As Victor Grimaldo mentioned… below worked for me very fine. As soon as I use the :parameter in my SQL query in SSRS dataset1.. it asked me to enter the values for these parameters, for which I choose already created SSRS parameters.
SELECT * FROM table a WHERE VALUE IN (**:parametername**)
Thanks Victor.