Meaning of ; in queries - sql-server

What is the meaning of ; at the end of queries?
For example; what is the difference between:
select 1
select 2
and
select 1;
select 2

"From a SQLServerCentral.Com article by Ken Powers:
The Semicolon
The semicolon character is a statement terminator. It is a part of the ANSI SQL-92 standard, but was never used within Transact-SQL. Indeed, it was possible to code T-SQL for years without ever encountering a semicolon.
Usage
There are two situations in which you must use the semicolon. The first situation is where you use a Common Table Expression (CTE), and the CTE is not the first statement in the batch. The second is where you issue a Service Broker statement and the Service Broker statement is not the first statement in the batch."
this is from When should I use semicolons in SQL Server? which might be what you are looking for
which is in turn "straight a cut and paste"
I think this might be stack overflows version of a joke.
edit: ; are also after merge statements

Using the ; is the correct way to end one statement and start another. If you do not use the ; you may get unexpected results

It is to denote the end of an Sql statement.

Giving a list of situation that are 'required' is always prone to omission. There are other situations besides commont table expression and SSB which the parser cannot handle w/o semicolon terminating the previous statement, like THROW or WITH XMLNAMESPACES and the list is bound to grow.
The correct answer is: semicolon terminators are required and should always be put whenever writing new code. Period. Omitting them is tolerated, but is on the official deprecation list:
Deprecated feature: Transact-SQL Not ending Transact-SQL statements with a semicolon
Replacement: End Transact-SQL statements with a semicolon ( ; ).
Ignoring this deprecation warning is on your own peril.

Related

How does the operator >+ differ from >= in SQL Server 2012

Entirely by accident today I was running a SQL statement to filter some items by date, for simplicity sake we'll say I used
SELECT *
FROM [TableName]
WHERE [RecordCreated] >+ '2016-04-10'
Only after the statement ran I realised I had used >+ instead of >=, now I was confused as I would have expected an error.
I tried a couple of other variations such as
>- -- Throws an error
<+ -- Ran successfully
<- -- Throws an error
The count of rows returned was exactly the same whether I used >= or >+
After searching online I couldn't find any documentation that covered this syntax directly, only when the two operators are used apart.
The RecordCreated column is a datetime.
Is this just a nicety in syntax for a possible common mistake or is it potentially trying to cast the date as a numeric value?
This seems to be a bug with '+' operator.
As per the updates from Microsoft team,
After some investigation, this behavior is by design since + is an
unary operator. So the parser accepts "+ , and the '+' is
simply ignored in this case. Changing this behavior has lot of
backward compatibility implications so we don't intend to change it &
the fix will introduce unnecessary changes for application code.
You can find a really good answer by RGO to his own question here.
The result shouldn't match with ">=" and "<=" but with ">" and "<". Just checked and the rowcound varies by 2 - the first and last item is removed.

Use of pipe symbol in Select clause

Is there any way/use of putting pipe symbol || in select clause.
I have come across following query in one of the article(probably to concatenate two values), but when I try to use the same in my query I am getting syntax error.
select FirstName ||''|| LastName As CustomerName from Customer
Please correct if I am using wrong syntax.
You can use CONCAT() function, which works in SQL Server 2012 and above, or just a plain + sign to do concatenation.
https://msdn.microsoft.com/en-us/library/hh231515(v=sql.110).aspx
Returns a string that is the result of concatenating two or more
string values.
you need to use '+' to perform Concat() instead of pipe if you are using SQL-Server. Pipe operator is not used in SQL-Server
It is used to concatenate you columns and output a single result i.e in one column.
For example, if i want to see first name and last name together as in one column then i could use pipes:
SELECT Fname||Lname FROM my_table;
If you are asking whether you can use pipes || for concatenation in Microsoft SQL, then the short answer is no.
If you’re asking about the concatenation operator itself, then read on.
|| is the standard ANSI concatenation operator. This is apparent in PostgreSQL, SQLite and Oracle, among others.
Microsoft, however uses +, because, why not. Except Microsoft Access uses &, because, why not.
MariaDB/MySQL have two modes. In traditional mode, || is interpreted as “or”, and there is no concatenation operator. In ANSI mode, || is interpreted as the concatenation operator.
Most DBMS (not SQLite) have the non-standard concat() function which will also concatenate. They also coalesce any NULLs to empty strings, so they’re a bit more forgiving if you don’t care about NULLs.

Escaping Strings in SQL Server

Am having issues with escaping parts of strings in SQL. On example is:
SELECT TOP 10000 *
FROM experience
WHERE name IS
'AT&T'
Which is saying incorrect syntax near Incorrect syntax near 'AT'. Seems its an issue with the & - is there any general rule to escaping?
Have also tried
SELECT TOP 10000 *
FROM experience
WHERE name Like
'AT&\T'
This works, although gives no results (there are results which should come up)
The only character that needs escaping in a string literal is the single quote. '. This is escaped by doubling them up instead of with a backslash.
SELECT 'O''Reilly'
In the vast majority of cases you should be using parameterised queries anyway and never need to even do that.
The correct operator to use is =
SELECT TOP 10000 *
FROM experience
WHERE name = 'AT&T'
Works Fine SQL Fiddle Demo
IS is only used in conjunction with [NOT] NULL
The only special significance backslash has in a string literal is if immediately before a line break when it acts as a line continuation character.
PRINT 'This is all \
one line'
Returns
This is all one line

Single-Double quotes error in Full Text Search

I am run into trouble.If type in Single-Double quotes in search statement will raise up a error,My sql statement like this:
SELECT UsersID,Sex,Age FROM dbo.UserBasicInfo WHERE
CONTAINS(PositionDesired,'"*"JAVA*"')
The error message:
Msg 7630, Level 15, State 3, Line 1
Syntax error near 'JAVA*' in the full-text search condition '"*"JAVA*"'.
Assume that the result must contains Single-Double quotes like: "JAVA"PHP" How to do?
Thanks !
You have an extra embedded double quote:
CONTAINS(PositionDesired,'"*"JAVA*"')
----------------------------^
This effectively terminates the string early, and SQL Server doesn't understand what that extra stuff is.
Should be (I think, not a full-text guru):
CONTAINS(PositionDesired,'"*JAVA*"')
However, I think that will eliminate the error, but not return the results you are after, since punctuation is ignored. You may have to use a combination of CONTAINS and LIKE, e.g.:
CONTAINS(PositionDesired,'JAVA')
AND PositionDesired LIKE '%"JAVA"%'
Or for the new requirement you've added:
CONTAINS(PositionDesired,'JAVA PHP')
AND PositionDesired LIKE '%"JAVA"PHP%"'
In the LIKE clause you don't have to worry about escaping or doubling-up the double quote, because it isn't a string delimiter there.
Hopefully the CONTAINS clause will filter results first, but even in a normal query there is no guarantee of short-circuiting or order of evaluation; I have no idea about a query with full-text and standard filters.

Why SQL Server doesn't treat this code erratic? [duplicate]

Shouldn't one of these statements work and one fail?
Intuition says Statement 2 should fail because there is a comma after int and no second column listed.
Yet both work and the trailing comma "," after the last column data type makes no difference.
-- Statement 1
CREATE TABLE dbo.MyTable1( col1 int);
-- Statement 2
CREATE TABLE dbo.MyTable2( col1 int,);
However (and this is expected): two commas ",," after the last field do cause a failure:
-- Statement 3
CREATE TABLE dbo.MyTable3( col1 int,,);
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ','.
Testing shows that its not just any character after the last field that is allowed through. For example, this fails:
-- Statement 3
CREATE TABLE dbo.MyTable3( col1 int ~);
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '~'.
Maybe SQL Server is "saving a seat at the table" for something? The Primary Key perhaps? I really don't know.
I am using Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64).
See http://connect.microsoft.com/SQLServer/feedback/details/273348/trailing-comma-allowed-in-create-table:
Description
When executing the CREATE TABLE command, a trailing comma following
the last column is allowed. Based on the grammar in BOL and comma
usage in lists in other T-SQL statements, this behavior is
inconsistent. This is a very minor issue and does not appear to cause
any adverse side-effects. It just appears that the parser may be a bit
off.
Microsoft views this as a bug, but a minor one.
This was resolved some time ago as "won't fix" but we didn't explain why. Simply, this seems pretty harmless, and not worth fixing in a service pack. We may consider fixing this in a future release.
It should be flagged as a syntax error, but there is a bug in SQL Server that doesn't treat the trailing comma as a syntax error.
Source: Microsoft Support (The affected versions in the list - 6, 6.5, and 2000 - are old, but I guess it's still around because it just worked for me in 2008.)
Almost all languages which permit comma-separated list items permit a comma after the last list item. This is done to make editing the program or file, and especially inserting new list items, easier. You don't have to worry about adding a comma after the current last list item, or removing a comma if you delete the old last list item.

Resources