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

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.

Related

UPDATE SET REPLACE function SQL

I keep getting errors when using the REPLACE function in SQL and i don't know why?
I execute this query:
UPDATE [ShellPlus].[dbo].[Views]
SET [ShellPlus].[dbo].[Views].SerializedProperties = REPLACE(SerializedProperties,'|EKZ PSG met verkort EEG','|EKZ PSG met verkort EEG|EEG kort op EEG3')
WHERE [ShellPlus].[dbo].[Views].InternalViewID = '3F4C1E8E-DA0C-4829-B447-F6BDAD9CD505'
And I keep getting this message:
Msg 8116, Level 16, State 1, Line 6
Argument data type ntext is invalid for argument 1 of replace function.
At UPDATE I give the correct table
At SET I give the correct column
At REPLACE I give the: (column name, 'old string', 'new string')
What am I doing wrong?
The real solution is fix the data type:
USE ShellPlus;
ALTER TABLE [dbo].[Views] ALTER COLUMN SerializedProperties nvarchar(MAX);
Then your existing query will work. But you should also normalise that data.
Try this:
UPDATE [ShellPlus].[dbo].[Views]
SET [ShellPlus].[dbo].[Views].SerializedProperties = CAST(REPLACE(CAST(SerializedPropertiesas NVarchar(MAX)),'|EKZ PSG met verkort EEG','|EKZ PSG met verkort EEG|EEG kort op EEG3') ) AS NText)
WHERE [ShellPlus].[dbo].[Views].InternalViewID = '3F4C1E8E-DA0C-4829-B447-F6BDAD9CD505'
Your doing at least three things wrong:
It seems like you're storing delimited data in your column - which is a mistake. For more information, read Is storing a delimited list in a database column really that bad?, where you will see a lot of reasons why the answer to this question is Absolutely yes!
You're using the Text data type, which is deprecated since SQL Server 2008 introduced varchar(max) to replace it. Given the fact that we're in 2019 and the 2008 version just ended it's extended support this July, its high time to change that Text data type to varchar(max) (and if you're using the 2008 or 2008 r2 version, upgrade your SQL Server).
You're using four-parts identifiers for your column names (Thanks #Larnu for pointing that out in the comments). Best practice is to use two-parts identifiers for column names. Read my answer here for a details explanation.
The solution to your problem involves refactoring the database structure - normalize what needs to be normalized, and replace of all Text, NText and Image with their modern replacement data types: varchar(max), nvarchar(max) and varbinary(max). Also, this would be a good time to figure out if you really need to support values longer than 8000 chars (4000 for unicode values) and if not, use a more appropriate value (max length columns have poor performance compared to "regular" length columns).

Setting the identifier quote character in Linq2Db

I find it hard to imagine that this question hasn't been asked before, but I couldn't find it.
I would like to use Linq2Db for Sybase and I need to change the identifier quoting characters from [ and ] to " and ", which is what Sybase uses. Is there anyway to do this? I tried looking at the linq2db source code once and it appears that these characters are hard coded, but I'm not sure (I think it would be silly to hard code them). Using Linq2db as it comes always produces errors around the "[" when Sybase executes the queries.
This is Sybase ASE 12.5, and it does not like [];
Here are some sample queries and the error message:
set quoted_identifier on
select * from "client" where clnt_id=140
select * from [client] where clnt_id=140
the first query works, but the second gives:
Incorrect syntax near '['. [SQLCODE=102, SQLSTATE="42000", Server=testtrng_ss1, Severity Level=15, State=1, Transaction State=1, Line=3]

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.

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.

What exactly does the T-SQL "LineNo" reserved word do?

I was writing a query against a table today on a SQL Server 2000 box, and while writing the query in Query Analyzer, to my surprise I noticed the word LineNo was converted to blue text.
It appears to be a reserved word according to MSDN documentation, but I can find no information on it, just speculation that it might be a legacy reserved word that doesn't do anything.
I have no problem escaping the field name, but I'm curious -- does anyone know what "LineNo" in T-SQL is actually used for?
OK, this is completely undocumented, and I had to figure it out via trial and error, but it sets the line number for error reporting. For example:
LINENO 25
SELECT * FROM NON_EXISTENT_TABLE
The above will give you an error message, indicating an error at line 27 (instead of 3, if you convert the LINENO line to a single line comment (e.g., by prefixing it with two hyphens) ):
Msg 208, Level 16, State 1, Line 27
Invalid object name 'NON_EXISTENT_TABLE'.
This is related to similar mechanisms in programming languages, such as the #line preprocessor directives in Visual C++ and Visual C# (which are documented, by the way).
How is this useful, you may ask? Well, one use of this it to help SQL code generators that generate code from some higher level (than SQL) language and/or perform macro expansion, tie generated code lines to user code lines.
P.S., It is not a good idea to rely on undocumented features, especially when dealing with a database.
Update: This explanation is still correct up to and including the current version of SQL Server, which at the time of this writing is SQL Server 2008 R2 Cumulative Update 5 (10.50.1753.0) .
Depending on where you use it, you can always use [LineNo]. For example:
select LnNo [LineNo] from OrderLines.

Resources