SQL Server character for enclosing database, table, field names - sql

I'm writing a script to create a bunch of tables, and I read in the Microsoft documentation that I should use tick marks (aka grave) to enclose database, table, and field names, but when I run it in SQL Server Management Studio, I get a syntax error on the first tick:
CREATE TABLE `active`.`test` ( … )
^syntax error
So I tried running it thru a lint, and it told me that ` is an invalid character, and it suggested removing them, which totally messed up the script.
What gives?

Use square brackets...
CREATE TABLE [active].[test](...)

The documentation you have linked to is:
The SQL query strings for Windows Installer are restricted to the following formats.
This is not the syntax for SQL Server. I suggest looking at the Transact-SQL Reference instead.
You need to use [] instead of the backtick:
CREATE TABLE [active].[test]

Related

PostgreSQL - I get SQL Error [42P01] or [42703] if I don't add double quotes around table names or Fields

I'm using DBeaver to write script for my PostgreSQL database.
I have a PostgreSQL DB with Tables autogenerated by C#/EFCore (Microsoft ORM) - I receive SQL Error [42P01] if I don't add double quotes around table names when I cut and paste my ORM queries to DBeaver. I got [42703] for fields without double quotes. I do not have to add double quotes in C# code but it appears to be required in DBeaver?
example:
select * from Dnp3PropertyBase => SQL Error [42P01]
select * from "Dnp3PropertyBase" => OK, all results shown...
Does anybody know if I can change a parameter in DBeaver somewhere in order to enter table names and fields without double quotes?
Note: Using DBeaver 22.3.2 (latest on 2023-01-11)
Update After reading: Postgresql tables exists, but getting "relation does not exist" when querying
show search_path => public, public, "$user"
SELECT * FROM information_schema.tables => All tables are in public schema
SELECT * FROM information_schema.columns => All columns are in public schema
Question: How to be able to cut and paste my EFCore generated queries from Visual Studio output window to DBeaver query without having any errors regarding table names and field names?
First let me copy #a_horse_with_no_name comment:
Unquoted names are folded to lower case in Postgres (and to uppercase
in Oracle, DB2, Firebird, and many others). So SomeTable is in fact
stored as sometable (or SOMETABLE). However quoted identifiers have to
preserve the case and are case sensitive then. So "SomeTable" is
stored as SomeTable
Many peoples recommended me to go with snake case which I didn't want to go with initialy because all tables were auto generated by EF Core (Microsoft C# ORM). I told myself that Microsoft would do standard things. Microsoft use the exact "class" name in code as the table name , by default. That appears to me very logical in order to stay coherent and apply the same rules everywhere. C# recommended to use Camel case for classes so each table names end by default in Camel case instead of snake case.
PostgreSQL seems to promote users to use snake casing because they lower case every non double quoted names. According to a_horse_with_no_name, and I think the same, only PostgreSQL has the behavior of lower casing down every table names and field names which are not double quoted in SQL script. That behavior (changing casing for non double quoted names) appears to me as being very limitative. It also has hidden effect that could be hard to find for non initiated peoples coming from other DB world.
According to PostgreSQL doc, they recommend to use nuget package (.UseSnakeCaseNamingConvention()). It probably works fine for TPH (table per hierarchy) which is recommended by Microsoft for performance. But it does not works for table name for TPC (table per class) because of actual bugs in EFCore 7 (see Github project).
I received that message at the end of "update-database":
Both 'WindTurbine' and 'ResourceGenerator' are mapped to the table
'resource_generator'. All the entity types in a non-TPH hierarchy (one
that doesn't have a discriminator) must be mapped to different tables.
See https://go.microsoft.com/fwlink/?linkid=2130430 for more
information.
PostgreSQL doc : TPH supported OK but not for table in TPC (2023-01-12). I use TPC then I had to force each table name directly through TableAttribute.
My solution For table name, I use snake casing by manually add a "Table" attribute to each of my classes with the proper name like this sample:
[Table("water_turbine")]
public class WaterTurbine : ResourceGenerator
For fields, I use the EFCore.NamingConventions NugetPackage which works fine for fields names. Don't forget that if you have 2 classes mapped to the same object, it is because you are using TPC and did not force table name through TableAttribute.
This way all my table and fields names are snake casing and I can cut and paste any query dumped in my debugger directly in any SQL script window of DBeaver (or any SQL tool).

visual studio 2012 query builder

Can anybody tell me what does the error mean? Whenever I open the query builder it will prompt with an error indicating that SQL syntax errors were encountered.
https://msdn.microsoft.com/en-us/library/ms189012.aspx
I looked at the following page in MSDN but I don't understand what it means...
For instance, what do these bullet points from the MSDN article mean?
The SQL statement is incomplete or contains one or more syntax errors.
The SQL statement is valid but is not supported in the graphical panes (for example, a Union query).
The SQL statement is valid but contains syntax specific to the data connection you are using.
USER (which you've apparently decided is an appropriate table name) is a SQL Server reserved word.
The best solution is to rename your table, so you don't have to escape the table name every time you want to query it and to make it clear it's your user data (hey, there's a table name suggestion - userdata).
The other option is to escape the name by surrounding it with square brackets:
SELECT * FROM [users]
Note that it will get old fast having to do this with every query. Again, the best solution would be to rename the table to something that isn't a reserved word.

table with "." in its name

I was trying to use sqlFetch. The fetch works perfectly when I change the name of my table to have underlines instead of periods. So if I use the command
sqlFetch(conn, "HelloWorld_40")
It works fine. Unfortunately, my friends are all using the real name of the table
sqlFetch(conn, "HelloWorld.40")
But then it crashes and it tells me that
Error in sqlColumns(conn, "HelloWorld.40") :
'HelloWorld.40': table not found on channel
I'm guessing the period "." is illegal name for a table. But I don't want my friends to change it because it's a lot of people who would be affected. Is there a way I can call the table, or do I have to secretly go to their database, change the name while I use it and then change it back to a period (risking that I will forget, someone will read, blah blah).
Thanks.
put the table name in square brackets:
[HelloWorld.40]
It is a problem with sqlFetch which parse table name. Unfortunately it did not handle table quotes, so it's search for table 40 in schema HelloWorld. You need to directly call sqlQuery (with quoted table name, brackets for MS SQL Server):
sqlQuery(dbhandle, "SELECT * FROM [HelloWorld.40]")
Side note: you should specify which database you are using.
The best delimiter is double quotes -- that should work in most underlying databases:
"HelloWorld.40"
In MySQL, you can also use back ticks (`):
`HelloWorld.40`
In SQL Server, Access, and I think Sybase, you can also use square braces:
[HelloWorld.40]

Is there a need to include brackets [] when running a query in SQL Server 2008?

I have SQL Server 2008 Express Edition installed and is my first time running a SQL query. I noticed that if I select to display the top 1000 rows that the query places brackets [] around the name of the database and its respective columns.
Why are there brackets around the name of the database and columns?
Is there a need to have these and if so when?
I just posted this answer on dba.stack.
They escape names that are not "friendly" - they can be useful if your database names contain special characters (such as spaces, dots or dashes) or represent SQL keywords (such as USE or DATABASE :-)). Without the square brackets, a query like this will fail:
SELECT column FROM database.dbo.table;
However if you write the query this way, the keywords are ignored:
SELECT [column] FROM [database].dbo.[table];
When building scripts or writing solutions that generate scripts from metadata (e.g. generating a script of all tables or all indexes), I always wrap entity names in square brackets so that they will work regardless of what kind of wonky names have been implemented (I am not always doing this for systems I control). You can do this easily using QUOTENAME function, e.g.:
SELECT QUOTENAME('table'), QUOTENAME('column'), QUOTENAME('database');
Results:
[table] [column] [database]
If you search my answers here for QUOTENAME you will find that I use it in a lot of scripts where I'm helping folks automate script generation or building dynamic SQL. Without the square brackets, a lot of people would run into issues running the scripts.
Enclosing a string in square braces is tells SQL Server that it should not try to parse whatever is inside them. This allows you to do use things like SQL reserved words (select, table, return, etc.) as well as spaces in identifiers. They are only required in those cases, but they are not harmful in any case.
No there isn't, but it ensures that if you had a db, table or column named as a reserved or keyword, for example date, that it wouldn't be confused with that keyword.

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

I've hit a bit of an impasse. I have a query that is generated by some C# code. The query works fine in Microsoft SQL Server Management Studio when run against the same database.
However when my code tries to run the same query I get the same error about an invalid column and an exception is thrown. All queries that reference this column are failing.
The column in question was recently added to the database. It is a date column called Incident_Begin_Time_ts .
An example that fails is:
select * from PerfDiag
where Incident_Begin_Time_ts > '2010-01-01 00:00:00';
Other queries like Select MAX(Incident_Being_Time_ts); also fail when run in code because it thinks the column is missing.
Any ideas?
Just press Ctrl + Shift + R and see...
In SQL Server Management Studio, Ctrl+Shift+R refreshes the local cache.
I suspect that you have two tables with the same name. One is owned by the schema 'dbo' (dbo.PerfDiag), and the other is owned by the default schema of the account used to connect to SQL Server (something like userid.PerfDiag).
When you have an unqualified reference to a schema object (such as a table) — one not qualified by schema name — the object reference must be resolved. Name resolution occurs by searching in the following sequence for an object of the appropriate type (table) with the specified name. The name resolves to the first match:
Under the default schema of the user.
Under the schema 'dbo'.
The unqualified reference is bound to the first match in the above sequence.
As a general recommended practice, one should always qualify references to schema objects, for performance reasons:
An unqualified reference may invalidate a cached execution plan for the stored procedure or query, since the schema to which the reference was bound may change depending on the credentials executing the stored procedure or query. This results in recompilation of the query/stored procedure, a performance hit. Recompilations cause compile locks to be taken out, blocking others from accessing the needed resource(s).
Name resolution slows down query execution as two probes must be made to resolve to the likely version of the object (that owned by 'dbo'). This is the usual case. The only time a single probe will resolve the name is if the current user owns an object of the specified name and type.
[Edited to further note]
The other possibilities are (in no particular order):
You aren't connected to the database you think you are.
You aren't connected to the SQL Server instance you think you are.
Double check your connect strings and ensure that they explicitly specify the SQL Server instance name and the database name.
In my case I restart Microsoft SQL Sever Management Studio and this works well for me.
If you are running this inside a transaction and a SQL statement before this drops/alters the table you can also get this message.
I eventually shut-down and restarted Microsoft SQL Server Management Studio; and that fixed it for me. But at other times, just starting a new query window was enough.
If you are using variables with the same name as your column, it could be that you forgot the '#' variable marker. In an INSERT statement it will be detected as a column.
Just had the exact same problem. I renamed some aliased columns in a temporary table which is further used by another part of the same code. For some reason, this was not captured by SQL Server Management Studio and it complained about invalid column names.
What I simply did is create a new query, copy paste the SQL code from the old query to this new query and run it again. This seemed to refresh the environment correctly.
In my case I was trying to get the value from wrong ResultSet when querying multiple SQL statements.
In my case it seems the problem was a weird caching problem. The solutions above didn't work.
If your code was working fine and you added a column to one of your tables and it gives the 'invalid column name' error, and the solutions above doesn't work, try this: First run only the section of code for creating that modified table and then run the whole code.
Including this answer because this was the top result for "invalid column name sql" on google and I didn't see this answer here. In my case, I was getting Invalid Column Name, Id1 because I had used the wrong id in my .HasForeignKey statement in my Entity Framework C# code. Once I changed it to match the .HasOne() object's id, the error was gone.
I've gotten this error when running a scalar function using a table value, but the Select statement in my scalar function RETURN clause was missing the "FROM table" portion. :facepalms:
Also happens when you forget to change the ConnectionString and ask a table that has no idea about the changes you're making locally.
I had this problem with a View, but the exact same SQL code worked perfectly as a query. In fact SSMS actually threw up a couple of other problems with the View, that it did not have with the query. I tried refreshing, closing the connection to the server and going back in, and renaming columns - nothing worked. Instead I created the query as a stored procedure, and connected Excel to that rather than the View, and this solved the problem.