Using SQL keywords as names without brackets - sql

Which keywords are allowed to be used as names without brackets and which are not ?
Why some SQL keywords are allowed to be used as names when others are not ?
Is there any pattern in determination of which I can use and which I can't without trying to compile and getting error ?
I have impression that older keywords are not allowed, but newer are allowed so that newer SQL versions are as compatible as possible with older.
In the following example rollup can be used as name without brackets, but group cannot.
if object_id('accident') is not null drop table accident
create table accident(
state varchar(50)
,city varchar(50)
,zip varchar(50)
,person varchar(50)
,id int identity(1,1)
)
insert accident(state,city,zip,person)values
('NY','Manhattan',10001,'John')
,('NY','Manhattan',10001,'John')
,('NY','Manhattan',10001,'Barbara')
;with
rollup as (
select accident.*
,lvl = grouping_id(accident.state,accident.city,accident.zip,accident.person,accident.id)
,accidents=count(1)
,people=0
from accident
group by rollup(accident.state,accident.city,accident.zip,accident.person,accident.id)
)
select * from rollup
;with
[group] as (
select accident.*
,lvl = grouping_id(accident.state,accident.city,accident.zip,accident.person,accident.id)
,accidents=count(1)
,people=0
from accident
group by rollup(accident.state,accident.city,accident.zip,accident.person,accident.id)
)
select * from [group]
Attempt to use group as name without brackets
;with
group as (
select accident.*
,lvl = grouping_id(accident.state,accident.city,accident.zip,accident.person,accident.id)
,accidents=count(1)
,people=0
from accident
group by rollup(accident.state,accident.city,accident.zip,accident.person,accident.id)
)
select * from group
gives error:
Msg 156, Level 15, State 1, Line 28
Incorrect syntax near the keyword 'group'.
Msg 156, Level 15, State 1, Line 36
Incorrect syntax near the keyword 'group'.

There is a list of reserved keywords and you can find it in here. It's too long to paste it into this answer. All reserved keywords have to be escaped. From your example rollup is not a reserved keyword, whereas group is.
There are more kywords in ISO standards. Plase take a look at the following notes in the same link:
Additionally, the ISO standard defines a list of reserved keywords. Avoid using ISO reserved keywords for object names and identifiers. The ODBC reserved keyword list, shown in the following table, is the same as the ISO reserved keyword list.
The ISO standards reserved keywords list sometimes can be more restrictive than SQL Server and at other times less restrictive. For example, the ISO reserved keywords list contains INT. SQL Server does not have to distinguish this as a reserved keyword.
Transact-SQL reserved keywords can be used as identifiers or names of databases or database objects, such as tables, columns, views, and so on. Use either quoted identifiers or delimited identifiers. Using reserved keywords as the names of variables and stored procedure parameters is not restricted.

Related

Using a bit column in a where clause

I am writing a very simple query where I need to retrieve the records based on a column that has two values: 0 and 1. I didn't realize this column has a bit type, therefore when I write the query SQL Server is giving me the message
"Incorrect syntax near the keyword 'Primary'."
My query is simple:
select * from [table name]
where Primary = '1'
I've tried searching the site but couldn't find a good answer. BTW, I only have access to retrieve the data from the table. I can't declare variables or create a stored procedure or any of that stuff. Surely this can't be that complicated. Please assist!
PRIMARY is reserved word and it needs to be quoted:
select * from [table name] where [Primary] = 1;
The problem has nothing to do with the datatype being a bit, the error, in fact, is telling you exactly what the problem is:
Incorrect syntax near the keyword 'Primary'.
Emphasis added.
PRIMARY is a reserved keyword. Ideally don't use keywords for object names, but if you "must" then you must delimit identify the object. In fact, really you should avoid any names for objects that require delimit identifing:
SELECT {Your Columns} --Define the columns, don't use *
FROM dbo.[Table Name] --I hope you don't have white space in your object names too
WHERE [Primary] = 1; --Don't wrap bit/numerical values in quotes.
That's because primary is a reserved word in SQL Server. You would need to quote it:
select * from [table name] where [Primary] = 1
I would warmly recommend changing the column name so it does not conflict with a langauge keyword. There are less than 200 reserved works in SQL Server, which leaves a lot of room for alternatives.
So:
sp_rename '[table name].[primary]', 'prim', 'COLUMN';

Left join ON not null columns can't select not null column

Each table has a column RECNUM. They are (decimal(28,0), not null). That is where I am doing my join. I want to select the column DESC in CAUNIT. It is (varchar(28,0), not null). When I run my query I get:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'DESC'. Below is my query:
SELECT CDCLSVC.UNIT_ID,CAUNIT.DESC
FROM CDCLSVC
LEFT JOIN CAUNIT
ON CDCLSVC.RECNUM = CAUNIT.RECNUM
The problem is with DESC column. In SQL Server it is a reserved keyword:
Microsoft SQL Server uses reserved keywords for defining,
manipulating, and accessing databases. Reserved keywords are part of
the grammar of the Transact-SQL language that is used by SQL Server to
parse and understand Transact-SQL statements and batches. Although it
is syntactically possible to use SQL Server reserved keywords as
identifiers and object names in Transact-SQL scripts, you can do this
only by using delimited identifiers.
Possible solution:
Rename column e.g. description
Quote it with []
You could also use aliases to avoid typing full table names:
SELECT cd.UNIT_ID,ca.[DESC]
FROM CDCLSVC cd
LEFT JOIN CAUNIT ca
ON cd.RECNUM = ca.RECNUM

What is the difference in [ ] and ( ) in SQL?

I've seen both used but I can't seem to understand when to use each?
To me is seems like you enter the name of the table you are referring from in the ( ) and the field name in the [ ]?
Could anyone explain?
The square brackets are used In Microsoft products to specify that what's within them is an identifier (the standard quoted identifiers are double quotes " ", which Microsoft SQL Sever also supports). This is used when you have a database name, user name, table name, field name, view name, procedure name (et.c.) that happens to be the same as a keyword, or contains characters that would break the syntax. This is often used in generated code to safeguard against identifiers that can't otherwise be used in the code. A generated query could look like this:
select [Id], [Name], [Password hint]
from [dbo].[MyDataBase].[User]
Here the field name Password hint would break the syntax if used without brackets, and the table name User could conflict with the keyword User.
Parentheses are used to group items, for example as part of the syntax of some clauses, for example an insert:
insert into someTable (field1, field2) values ('value1', 'value2')
They can also be used in expressions:
select Price * (Quantity + FreeItems) from Articles
They can also be used around queries to make subqueries:
select o.Name
from (select Name, Age from Persons where City = 'Oslo') as o
where o.Age > 18
() are used for passing parameters to functions and stored proceedures etc. [] are used to encapsulate field name (etc.) which include punctuation (spaces and special characters as per the comment above). [] are useful sometimes to name fields for display
SELECT FFgg AS [Some field discription] FROM table1;
Hope this helps.

Select table with column named "index"

I have a table with a column name called "index"
select id, index
from item;
gives an error:
Msg 1018, Level 15, State 1, Line 1 Incorrect syntax near 'index'. If
this is intended as a part of a table hint, A WITH keyword and
parenthesis are now required. See SQL Server Books Online for proper
syntax.
How can I do a select on a column named index? I'm using sqlserver 2008-R2
Use square brackets to quote reserved words:
select id, [index]
from item
See also the documentation on Delimited Identifiers.
Put reserved words in brackets:
select id, [index]
from item
Try this
SELECT id, [index] FROM item
Reserved words used as names in SQL-Server must be enclosed in brackets.

[] brackets in sql statements

What do the brackets do in a sql statement?
For example, in the statement:
insert into table1 ([columnname1], columnname2) values (val1, val2)
Also, what does it do if the table name is in brackets?
The [] marks the delimitation of a identifier, so if you have a column whose name contains spaces like Order Qty you need to enclose it with [] like:
select [Order qty] from [Client sales]
They are also to escape reserved keywords used as identifiers
This is Microsoft SQL Server nonstandard syntax for "delimited identifiers." SQL supports delimiters for identifiers to allow table names, column names, or other metadata objects to contain the following:
SQL reserved words: "Order"
Words containing spaces: "Order qty"
Words containing punctuation:
"Order-qty"
Words containing international
characters
Column names that are
case-sensitive: "Order" vs. "order"
Microsoft SQL Server uses the square brackets, but this is not the syntax standard SQL uses for delimited identifiers. Standardly, double-quotes should be used for delimiters.
In Microsoft SQL Server, you can enable a mode to use standard double-quotes for delimiters as follows:
SET QUOTED_IDENTIFIER ON;
They are meant to escape reserved keywords or invalid column identifiers.
CREATE TABLE test
(
[select] varchar(15)
)
INSERT INTO test VALUES('abc')
SELECT [select] FROM test
They allow you to use keywords (such as date) in the name of the column, table, etc...
Since this is a bad practice to begin with, they are generally not included. The only place you should see them being used is by people starting out with sql queries that don't know any better. Other than that they just clutter up your query.
Anything inside the brackets is considered a single identifier (e.g. [test machine]. This can be used to enclose names with spaces or to escape reserve words (e.g. [order], [select], [group]).
if you use any column name which is same as any reserved keyword in sql, in that case you can put the column name in square bracket to distinguish between your custom column name and existing reserved keyword.
When having table names or filenames with spaces or dashes (-) etc... you can receive "Systax error in FROM clause".
Use [] brackets to solve this.
See: https://msdn.microsoft.com/en-us/library/ms175874.aspx
They are simply delimiters that allow you to put special characters (like spaces) in the column or table name
e.g.
insert into [Table One] ([Column Name 1], columnname2) values (val1, val2)