#table in FROM clause - sql

My manager (not currently working in an IT environment) sent me a chunk of code to run some data however one line confuses me. For some context, this is ORACLE SQL.
She has a line set as "FROM ma1 #proddb m1"
I'm not currently sure what it does or even trying to achieve. It's hard for me to visualize it since I do not have access to the database itself.
What's the proper syntax for that line as that's where I'm currently getting errors. Thank you!

What's the proper syntax for that line as that's where I'm currently getting errors.
# indicates a database link
The syntax is:
FROM table_name#dblink table_alias
So for you:
ma1 is the name of the table/view/materialized view.
proddb is the name of the database link.
m1 is the table alias.
The only thing that is wrong with your syntax is that you need to remove the space character between ma1 and #proddb. If you do that then it should work assuming that the database link and the remote table/view/materialized view exist.

"FROM ma1#proddb m1" -> ma1 is a table from a different DB, with #my_remote_DB you have access to objects on a remote database. In your case proddb is your remote database link.

Related

Hive "Show Tables" Fails with MetaException

Using Hive 2.3.7 on AWS EMR (5.33.1) I have created a database which shows correctly when calling show databases;. I then create a table which seems to work correctly (no exceptions). When I call describe <table>; It correctly returns the name and schema of the table. However when I run show tables; the following error is returned:
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask.MetaException(message:Got exception: org.apache.hadoop.hive.metastore.api.MetaException
Exception thrown when executing query :
SELECT A0.TBL_NAME,A0.TBL_NAME AS NUCORDER0 FROM TBLS A0 LEFT OUTER JOIN DBS B0 ON
A0.DB_ID = B0.DB_ID WHERE B0.`NAME` = ? AND LOWER(A0.TBL_NAME) LIKE '_%' ESCAPE '\' ORDER BY NUCORDER0)
If anyone can shed any light on this issue it would be really appreciated.
I have googled around and found nothing of any use.
EDIT: show tables in <schema>; returned the same result
EDIT 2: This issue was solved by updating the EMR to emr-6.4.0. I have no great insight into the issue beyond what is mentioned here.
I think your metadata database has been corrupted/has bad data. I would take a backup. And then see if you can restore some previous backups. I would connect to the database directly and look at the those tables and see if anything looks out of the ordinary. If you find a bad table entry don't delete it. I'd try using "Delete table" commands (via hive) to remove it to keep integrity. If you have to you can delete entries in your database, you have a backup and could restore back the tables.
Hive meta store is using datanucleus, https://www.datanucleus.org/, for all CRUD of metastore database. It's generating \\ to escape backslash itself, but Mariadb interprete \\ as string literal. So it needs to use \\ as escape character.
You can see sql_mode setting here, https://mariadb.com/kb/en/sql-mode/#sql_mode-values.
Get rid of NO_BACKSLASH_ESCAPE from the mode and it should be all right.
Try providing the schema which you want to see the tables:
show tables in schema_name;

Identical SQL query works on some tables but errors out on other tables same in the same DB

I'm a finance person (little programming background) so I maybe asking something obvious for database programming experts but will appreciate any advice
Background:
I'm accessing Oracle NetSuite database via ODBC from Microsoft SQL Management Studio
Connection as a Linked Server is established successfully
I'm trying to execute the following SQL statements:
select * from [NETSUITE_SB2].[SB-B].[Administrator].[VARIANCE] -- success
select * from [NETSUITE_SB2].[SB-B].[Administrator].[WTAX_JOB] -- "Msg 7314, Level 16, State 1, Line 1
The OLE DB provider "MSDASQL" for linked server "NETSUITE_SB2" does not contain the table ""SB-B"."Administrator"."WTAX_JOB"". The table either does not exist or the current user does not have permissions on that table."
Upon some testing, it appears that whether the query is successfully run depends on whether the table name contains "_" (underscore) - for all tables without underscore I've tried, it worked, for all tables with underscore that I've tried, it failed.
Can anyone help me figure out how to overcome this?
Thanks in advance!
Instead of using a 4-part name in SQL Server and having SQL Server generate a query for the linked server, try using the OPENQUERY function and passing a query in the target system's SQL dialect directly. Something like:
select *
from OPENQUERY([NETSUITE_SB2], 'select * from [SB-B].[Administrator].[WTAX_JOB]' )
I just encountered this myself in a new instance that I just set up. I had been using Suite Connect for 4+ years without running into this issue before.
I believe the issue with the situation here is the "[SB-B]" part of the name because it contains the "-" dash. I found that a "," comma or "." period were the issue with my name [Acme, Inc.]. Ether the period or comma threw the error.
The second part of the 4-part name is the NetSuite [Company Name] under General Settings Company Info. I changed the name in NetSuite and removed the comma and period and the problem went away. Maybe most special characters cause the issue?
Just remember you'll have to update your second part name in each query you created before.
While using OPENQUERY is a solution, I just don't like the extra quotes needed so I prefer normal SQL.

SQL71501 - How to get rid of this error?

We're using two schemas in our project (dbo + kal).
When we are trying to create a view with the following SQL statement, Visual Studio shows as an error in the error list.
CREATE VIEW [dbo].[RechenketteFuerAbkommenOderLieferantenView]
AS
SELECT
r.Id as RechenkettenId,
r.AbkommenId,
r.LieferantId,
rTerm.GueltigVon,
rTerm.GueltigBis,
rs.Bezeichnung,
rs.As400Name
FROM
[kal].[Rechenkette] r
JOIN
[kal].[RechenketteTerm] rTerm ON rTerm.RechenketteId = r.Id
JOIN
[kal].[Basisrechenkette] br ON rTerm.BasisrechenketteId = br.Id
JOIN
[kal].[Rechenkettenschema] rs ON rs.Id = br.Id
WHERE
r.RechenkettenTyp = 0
The error message looks like this:
SQL71501: Computed Column: [dbo].[RechenketteFuerAbkommenOderLieferantenView].[AbkommenId] contains an unresolved reference to an object. Either the object does not exist or the reference is ambiguous because it could refer to any of the following objects:
[kal].[Basisrechenkette].[r]::[AbkommenId], [kal].[Rechenkette].[AbkommenId], [kal].[Rechenkette].[r]::[AbkommenId], [kal].[Rechenkettenschema].[r]::[AbkommenId] or [kal].[RechenketteTerm].[r]::[AbkommenId].
Publishing the view and working is just fine, but its quite annoying to see the error message all the time when building our project having all the serious errors get lost in the shuffle of those sql errors.
Do you have any idea, what the problem might be?
I just found the solution. Although I can't read your (what appears to be German) enough to know if you're referring to system views, if so, a database reference to master must be provided. Otherwise, adding any other required database references should solve the problem.
This is described here for system views: Resolve reference to object information schema tables
and for other database references.
Additional information is provided here: Resolving ambiguous references in SSDT project for SQL Server
For me I was seeing SQL71501 on a user defined table type. It turned out that the table type's sql file in my solution wasn't set as build. As soon as I changed the build action from None to Build, the error dissapeared.
I know this is an old question but it was the first one that popped up when searching for the error.
In my case the errors were preventing me from executing the SqlSchemaCompare in Visual Studio 2017. The error however was for a table/index of a table that was not part of the solution any more. A simple clean/rebuild did not help.
A reload of the visual studio solution did the trick.
We have a project that contains a view that references a table valued function in another database. After adding the database reference that is required to resolve the fields used from the remote database, we were still getting this error. I found that the table valued function was defined by using "SELECT * FROM ..." which was old code created by someone not familiar with good coding practices. I replaced the "*" portion with the enumerated fields needed and compiled that function, then re-created the dacpac for that database to capture the resulting schema, and incorporated the new dacpac as the database reference. Woo Hoo! the ambiguous references went away! Seems that SSDT engine cannot (or does not) always have the ability to reach down into the bowels of the referenced dacpac to come back with all the fields. For sure, the projects I work on are normally quite large, so I think it makes sense to give the tools all the help you can when asking them to validate your code.
Although this is an old topic, it is highly ranked on search engines, so I will share the solution that worked for me.
I faced the same error code with a CREATE TYPE statement, which was in a script file in my Visual Studio 2017 SQL Server project, because I couldn't find how to add a user-defined type specifically from the interface.
The solution is that, in Visual Studio, there are many programmability file types, other than the ones you can see through a right-click > Add. Just select New Element and use the search field to find the element you are trying to create.
From the last paragraph of the blog post Resolving ambiguous references in SSDT project for SQL Server, which was linked in the answer https://stackoverflow.com/a/33225020/15405769 :
In my case, when I double clicked the file and opened it I found that
one of the references to ColumnX was not using the two part name and
thus SSDT was unable to determine which table it belonged to and
furthermore whether the column existed in the table. Once I added the
two part name. Bingo! I was down to no errors!
In my case, I got this error when I was trying to export the datatier application. The error was related to the link on a database user. To solve the problem, you need to log in to the server with read rights on system users.
In my case I just double click on the error and it will take me to the exact error on procedure and I noticed that table column is deleted or renamed but in SP its still using the old column name.
If you build an SSDT project you can get an error which says:
“SQL71502: Function: [XXX].[XXX] has an unresolved reference to object [XXX].[XXX].”
If the code that is failing is trying to use something in the “sys” schema or the “INFORMATION_SCHEMA” schema then you need to add a database reference to the master dacpac:
Add a database reference to master:
Under the project, right-click References.
Select Add database reference….
Select System database.
Ensure master is selected.
Press OK.
Note that it might take a while for VS to update.
(Note this was copied verbatim from the stack overflow question with my screenshots added: https://stackoverflow.com/questions/18096029/unresolved-reference-to-obj… - I will explain more if you get past the tldr but it is quite exciting! )
NOT TLDR:
I like this question on stack overflow as it has a common issue that anyone who has a database project that they import into SSDT has faced. It might not affect everyone, but a high percentage of databases will have some piece of code that references something that doesn't exist.
The question has a few little gems in it that I would like to explore in a little more detail because I don't feel that a comment on stack overflow really does them justice.
If we look at the question it starts like this:
If you're doing this from within Visual Studio, make sure that the file is set to "Build" within the properties.
I've had this numerous times and it really gets me everytime. SQL Build is case sensitive even though your collation isn't. Check the case is correct in agreement with the object and schema names that are referenced!

Syntax error on executing a script in Sybase database

I created a Sybase database emp_details using SQL Anywhere and Sybase Central. I had given emp/emp as dba username/password while creating.
The db got created and the files were generated in the given folder.
When I tried running the below script using Ineractive SQL:
use master
go
if exists (select 1 from master..sysdatabases where name='emp_details')
checkpoint emp_details
go
It threw the following exception
Could not execute statement.
Syntax error near 'checkpoint' on line 2
SQLCODE=-131, ODBC 3 State="42000"
Line 4, column 1
Haven't been able to figure out what exactly the syntax issue is and have been stuck up with this for a while.
Any ideas?
First of all, you may want to think about posting your SQL Anywhere questions to the http://sqlanywhere-forum.sap.com/ forum. It's a forum dedicated to the SQL Anywhere product line.
Is there any possibility that the two periods together might be causing your syntax issue?
Normally you're not going to get an exact area where the error is coming from. See if that helps. Also check out the other forum as well.

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.