sql server 2005 express - Invalid Object Name error - sql

I have a copy of a query from a view (by filtering) and when i tried to excute it, it throws an error message that says "invalid object name 'bla bla'".
How can i fix it?
I am using windows 7(ultimate) os and sql server 2005 express.

You may be executing the query in the wrong database. If you are running it manually in SSMS, use the 'use' statement or the 'available databases' drop down list to select the correct db.
Or fully qualify the name of the object you are accessing (db_name.owner.object_name).
Or, as rlb.usa suggests, maybe the object just doesn't exist. (check your spelling...)

It can happen two ways:
You have table, procedure, or function name(s) that do not exist.
You can fix this by verifying the object does indeed exist. Check this one first. Is the spelling correct? Is the schema correct? (dbo.mytable != user.mytable)
SQL wants you to use "qualified" names.
You can fix this by putting use mydatabasename; at the top of your query, before the query itself. If it doesn't like that one, you can then try the longer method of using qualified names by prefixing all of your tables, functions, and procedures as databasename.schema.object .

Related

Correct VBA Syntax for DB2 Command?

I'm attempting to connect to DB2 through VBA. I have a connection established through the ODBC provider.
Here's the string of my command text looks like:
strCmd = "INSERT INTO mySchema.myTable (Text) VALUES ('Test')"
When I run this, I get the following runtime error:
[IBM][CLI Driver][DB2/NT64] SQL0204N "MYSCHEMA.MYTABLE" is an undefined name. SQLSTATE=42704
I have validated and verified that the schema and table exist in DB2. I have validated (by using another tool - IBM Data Studio - that the credentials have access and authority to write to this table.
Is my syntax wrong? Is there something I'm missing? If I don't add the "MYSCHEMA." in front of the table name, it presumes I want the "ADMIN" schema, which I don't (it doesn't even exist).
How do I successfully execute an insert command to DB2 LUW?
This is frequently asked.
Db2 automatically folds unquoted object names into uppercase.
This makes programming easier because being forced to quote objects is not so friendly.
It means that "myTable"."mySchema" is a different object than MYTABLE.MYSCHEMA.
So in general it is easier to configure your toolset to not quote object names when creating the objects, and so allow them to be folded to uppercase. It also allows subsequent queries to avoid having to quote table names and column names.
But sometimes you don't have a choice.

Dynamic SQL error in Talend

I'm learning Talend. I'm trying to connect to a DB and just pull tables from it.
I've managed to create the connection metadata and was able to connect to the SQL Server DB.
However, when I drag&drop the connection into the job (as a tsMSSqlInput) and run the job, I get the following error :
Exception in component tMSSqlInput_1
[FATAL]: talend_train.engia_test_0_1.ENGIA_Test - tMSSqlInput_1 An object or
column name is missing or empty. For SELECT INTO statements, verify each
column has a name. For other statements, look for empty alias names. Aliases
defined as "" or [] are not allowed. Change the alias to a valid name.
java.sql.SQLException: An object or column name is missing or empty. For
SELECT INTO statements, verify each column has a name. For other statements,
look for empty alias names. Aliases defined as "" or [] are not allowed.
Change the alias to a valid name.
My guess is something wrong with the dynamic query (using context variables) :
"SELECT \""+context.Engica_Connect_Schema+"\".CM_AU_TA.AU_TA_UN,
\""+context.Engica_Connect_Schema+"\".CM_AU_TA.AU_TA_TN,
\""+context.Engica_Connect_Schema+"\".CM_AU_TA.AU_TA_PK,
\""+context.Engica_Connect_Schema+"\".CM_AU_TA.AU_TA_SK,
\""+context.Engica_Connect_Schema+"\".CM_AU_TA.AU_TA_FN,
\""+context.Engica_Connect_Schema+"\".CM_AU_TA.AU_TA_OV,
\""+context.Engica_Connect_Schema+"\".CM_AU_TA.AU_TA_NV,
\""+context.Engica_Connect_Schema+"\".CM_AU_TA.AU_TA_ID,
\""+context.Engica_Connect_Schema+"\".CM_AU_TA.AU_TA_DT,
\""+context.Engica_Connect_Schema+"\".CM_AU_TA.SY_FI_DA,
\""+context.Engica_Connect_Schema+"\".CM_AU_TA.SQL_TIMESTAMP"
+"
FROM \""+context.Engica_Connect_Schema+"\".CM_AU_TA"
Something must be wrong with the double quotes, I'm not sure where or how.
Also, when I try to run the query to get a preview heres what I got :
Incorrect Syntax error
Any ideas please ?

How do I pass system variable value to the SQL statement in Execute SQL task?

SSIS 2008. Very simple task. I want to retrieve a System Variable and use it in an SQL INSERT. I want to retrieve the value of System:MachineName and use it in an insert statement.
Using the statement INSERT INTO MYLOG (COL1) SELECT #[System::MachineName] gives the error Error: ..failed to parse. Must declare the scalar variable "#"
Using the statements SELECT #System::MachineName or SELECT ##[System::MachineName] gives the error 'Error Incorrect systax near '::'
I am not trying to pass a parameter to the query. I have searched for a day already but couldn't find how to do this one simple thing!
Here is one way you can do this. The following sample package was created using SSIS 2008 R2 and uses SQL Server 2008 R2 as backend.
Create a sample table in your SQLServer database named dbo.PackageData
Create an SSIS package.
On the SSIS, add an OLE DB connection manager named SQLServer to connect to your database, say to an SQL Server database.
On the Control flow tab, drag and drop an Execute SQL Task
Double-click on the Execute SQL task to bring the Execute SQL Task Editor.
On the General tab of the editor, set the Connection property to your connection manager named SQLServer.
In the property SQLStatement, enter the insert statement INSERT INTO dbo.PackageData (PackageName) VALUES (?)
On the Parameter Mapping tab, click Add button, select the Package variable that you would like to use. Change the data type accordingly. This example is going to insert the PackageName into a table, so the Data Type would be VARCHAR. Set the Parameter Name to 0, which indicates the index value of the parameter. Click OK button.
Execute the package.
You will notice a new record inserted into the table. I retained the package name as Package. That's why the table
Hope that helps.
Per my comment against #ZERO's answer (repeated here as an answer so it isn't overlooked by SSIS newcomers).
The OP's question is pretty much the use case for SSIS property expressions.
To pass SSIS variables into the query string one would concatenate it into an expression set for the SqlStatementSource property:
"INSERT INTO MYLOG (COL1) SELECT " + #[System::MachineName]
This is not to suggest the accepted answer isn't a good pattern, as in general, the parameterised approach is safer (against SQL injection) and faster (on re-use) than direct query string manipulation. But for a system variable (as opposed to a user-entered string) this solution should be safe from SQL injection, and this will be roughly as fast or faster than a parameterised query if re-used (as the machine name isn't changing).
I never use it before but maybe you can check out the use of expression in Execute SQL task for that.
Or just put the whole query into an expression of a variable with evaluateAsExpression set to true. Then use OLE DB to do you insert
Along with #user756519's answer, Depending on your connection string, your variable names and SQLStatementSource Changes

How can I programmatically run arbitrary SQL statements against my Hibernate/HSQL database?

I'm looking for a way to programmatically execute arbitrary SQL commands against my DB.
(Hibernate, JPA, HSQL)
Query.createNativeQuery() doesn't work for things like CREATE TABLE.
Doing LOTS of searching, I thought I could use the Hibernate Session.doWork().
By using the deprecated Configuration.buildSesionFactory() seems to show that doWork won't work.
I get "use lacks privilege or object not found" for all the CREATE TABLE statements.
So, what other technique is there for executing arbitratry SQL statements?
There were some notes on using the underlying JDBC Statement, but I haven't figure out how to get a JDBC Connection object from Hibernate to try that.
Note that the hibernate.hbm2ddl.auto=create setting will NOT work for me, as I have ARRAY[] columns which it chokes on.
I don't think there is any problem executing a create table statement with a Hibernate native query. Just make sure to use Query.executeUpdate(), and not Query.list() or Query.uniqueResult().
If it doesn't work, please tell us what happens when you execute it, and join the full stack trace of the exception and the SQL query you're executing.
"use lacks privilege or object not found" in HSQL may mean anything, for example existence of a table with the same name. Error messages in HSQL are completely misleading. Try listing your tables using DatabaseMetadata - you have probably already created the table.

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.