Select a field from table that contains parenthesis - sql

I'm wondering if it's possible to have a fieldname with parenthesis () and be able to call it with a query. For example I have a field name called...
EnoughMoney(0)
Select EnoughMoney(0) from tbl1
When I select it in SSMS i get the following error....
'EnoughMoney' is not a recognized built-in function name.

The way you can escape names (of columns or of anything else) in SQL Server is by enclosing them in square brackets. Your query will work if you write it like
select [EnoughMoney(0)] from tbl1
As correctly stated by others, it's usually a good practice to avoid spaces and special characters in database objects' names, unless you are forced to, obviously.

Use Select [EnoughMoney(0)] from tbl1

Related

SQL keyword as column name [duplicate]

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

How to select values around .(dot) using sql

I am running below query in Teradata :
sel requesttext from dbc.tables
where tablename='old_employee_table'
Result:
alter table DB_NAME.employee_table,no fallback ;
I want to get below result using SQL:
DB_NAME.employee_table
Requesttext can be:
create set table DB_NAME.employee_table;
DB Name and table can occur anywhere in the result. Since .(dot) is joining them that's why i want to split with .(dot).
Basically I need sql which can result me surrounding values of .(dot)
I want DBName and Tablename in result.
I'm not a Teradata person, but this should work for both strings given so far, as long as teradata's regexp_substr() supports positive look-behind and positive look-ahead assertions (I might have the Teradata syntax wrong, so a little tweaking may be needed):
SELECT REGEXP_SUBSTR(requesttext, '(?<= )(\w+\.\w+)(?=[,$]?)', 1, 1)
FROM dbc.tables
WHERE tablename='old_employee_table'
See the regex101 example. Hopefully it translates to Teradata easily.
The regex looks for and returns the words either side of and including the period, when preceded by a space, and followed by an optional comma or the end of the line.
You could do this with either regexp_substr() or strtok().
As Jamie Zawinski said:
Some people, when confronted with a problem, think "I know, I'll use
regular expressions." Now they have two problems.
So I would go with the strtok() method. Also I'm lazy and regular expressions are hard.
Function strtok() takes three arguments:
The string being split
The delimiter to split the string
The number of the token to grab.
To get at the <database>.<table> from that string that is returned in your query, we can split by a space, grab the third token, then split that by a comma and grab the first token.
That would look like:
SELECT strtok(strtok(requestText,' ',3),',',1)
FROM dbc.tables
WHERE tablename='old_employee_table'

Escaping special characters when naming a table column without setting define off

Before I posted my question, I read up various posts on this site about how to escape a special character when inserting a new field value or looking for a field name in the where clause. What I did not find was how to escape a special character when you want to name a table or column with one.
So, I want to name fieldA as this&that, e.g.
select fieldA this&that from tableA
I also want to use a substitution variable (&var) in the same query, so set define off wouldn't help.
I tried to use 'this' || chr(38) || 'that' with or without single quotes, but SQL Developer doesn't like either.
Any ideas?
You would need to quote the identifier, but this is a really bad idea; every reference to the column everywhere will also have to be quoted and match the case exactly. See this, and the documentation, which advises against using quoted identifiers.
It's an even worse idea with an ampersand because of its use for substitution variables, as you're seeing. To create the table and then use substitution variables in the same script you would need to turn off defines before the creation, and then turn them back on afterwards:
set define off
create table bad_idea("this&that" number);
set define on
But you still couldn't refer to the table name and a substitution variable in the same statement, unless you set define to something non-standard:
set define "^"
insert into bad_idea("this&that") values (^var);
But again everything that ever refers to that column will need to take that into account too, as well as the case and quoting.
I'd seriously reconsider and make it something like this_and_that, or omit the 'and' part completely if it isn't really adding anything (or your real column name is approaching the length limit).
If you only need it as a column alias you can do the same thing, and it would be slightly less painful, but still not ideal:
set define "^"
select fieldA "this&that" from tableA where fieldB = ^var;

WHERE Clause Requires Like When Equals Should Work

I have a query that I think should look like this:
select *
from Requesters
where CITIZEN_STATUS = 'OS-IE ';
The field CITIZEN_STATUS, whose data type is varchar(15), has a trailing space for this particular value. I have pasted it into Notepad++ and looked at it with a hex editor, and the final space is indeed 0x20.
For the query to work, I have to write it like this:
select *
from Requesters
where CITIZEN_STATUS like 'OS-IE%';
So, obviously, I have a workaround and the question is not urgent. But I would really like to know why the first query fails to do what I expect. Does anyone have any ideas?
I should mention I am using SQL Server 2005 and can provide more information about the configuration if needed.
In MySQL 5, this query works. However, it does not distinguish on trailing whitespace. The query matches 'OS-IE ' as well as 'OS-IE'. In SQL Server 2005 you can use a regular expression that defines the end of a line. The correct character for this is the dollar sign '$' to indicate that you do want the space. See http://msdn.microsoft.com/en-us/magazine/cc163473.aspx

Insert double quotes into SQL output

After I run a query and view the output, for example
select * from People
My output is as follows
First Last Email
Ray Smith raysmith#whatever.itis
How would I export this data so that it looks as follows?
"Ray","Smith","raysmith#whatever.itis"
Or is there a way to do this within SQL to modify records to contain quotes?
Because when you export, it's going to include the commas anyway, right?
If the columns you're interested in are 128 characters or less, you could use the QUOTENAME function. Be careful with this as anything over 128 characters will return NULL.
SELECT QUOTENAME(First, '"'), QUOTENAME(Last, '"'), QUOTENAME(Email, '"')
FROM People
select '"'+first+'","'+last+'","'+email+'"'
from people
This is the kind of thing best done in code however, you shouldn't query for presentation.
select concat(“\"”,first,“\"”,“\"”,Last,“\"”,“\"”,Email,“\"”) as allInOne
Modifying the records to contain quotes would be a disaster; you don't use the data only for export. Further, in theory you'd have to deal with names like:
Thomas "The Alley Cat" O'Malley
which presents some problems.
In Standard SQL, you'd use doubled-up single quotes to enclose single quotes (with no special treatment for double quotes):
'"Thomas "The Alley Cat" O''Malley"'
Some DBMS allow you to use double quotes around strings (in Standard SQL, the double quotes indicate a 'delimited identifier'; SQL Server uses square brackets for that), in which case you might write the string as:
"""Thomas ""The Alley Cat"" O'Malley"""
Normally, though, your exporter tools provide CSV output formatting and your SQL statement does not need to worry about it. Embedded quotes make anything else problematic. Indeed, you should usually not make the DBMS deal with the formatting of the data.
This worked best for me
SELECT 'UPDATE [dbo].[DirTree1] SET FLD2UPDATE=',QUOTENAME(FLD2UPDATE,'''')
+' WHERE KEYFLD='+QUOTENAME(KEYFLD,'''')
FROM [dbo].[Table1]
WHERE SUBSTRING(FLD2UPDATE,1,2) = 'MX'
order by 2
If you are using MS SQL Server, try something like:
SELECT '"'||Table.Column||'"'
FROM Table
-- Note that the first 3 characters between "SELECT" and "||" are:
' " '
-- The characters are the same after "||" at the end... that way you get a " on each side of your value.