SQL - Table not found after backup - sql

I saved a SQL table before deleting some information from it with the sql statment:
select * into x_table from y_table
After doing some operations, I want to get back some information from the table I saved with the query above. Unfortunately, MS SQL Server MGMTS shows an error saying that the table does not exist.
However, when I put the drop statement, the table is recognized - and the table is not underlined.
Any idea why this table is recognized by the drop table statement and not the select from statement. This seems strange for me.
EDIT:
Thank you

It may be that the table isn't underlined in your drop table command because its name is still in your IntelliSense cache. Select Edit -> IntelliSense -> Refresh Local Cache in SSMS (or just press Ctrl+Shift+R) and see if the table name is underlined then.
Edit:
Another possibility is that your drop table command might be in the same batch as another statement that creates the table, in which case SSMS won't underline it because it knows that even though the table doesn't exist now, it will exist by the time that command is executed. For instance:
None of the tables one, two, or three existed in my database when I took this screenshot. If I highlight line 6 and try to run it by itself, it will fail. Yet you can see that two is not underlined on line 6 because SSMS can see that if I run the whole script, the table will be created on line 5. On the other hand, three is underlined on line 9 because I commented out the code that would have created it on line 8.
All of that said, I think we might be making too much of this problem. If you try to select from a table and SQL Server tells you it doesn't exist, then it doesn't exist. You can't rely on IntelliSense to tell you that it does; the two examples above are probably not the only ways that IntelliSense might mislead you about the current status of a table.
If you want the simplest way to know whether an object with a given name (like x_table) exists, just use:
select object_id('x_table');
If this query returns null, x_table doesn't exist, regardless of what IntelliSense is telling you. If it returns non-null, then there is some object out there with that name, and then the real question is why your select statement is failing. And to answer that, I'd need to see the statement.

A lot of posts like this, you have to copy in 2 statements :
CREATE TABLE newtable LIKE oldtable;
INSERT newtable SELECT * FROM oldtable;

Related

Running a basic select on SQL Sever asks for column name that doesn't exist, why?

We had another developer come through and complete some work for us. Unfortunately he didn’t work well within our team and management let him go.
Because of this now I’m stuck debugging his code and undoing work that was done. He did not document his code (one of the reasons he was let go), rarely notating anything, therefore I have no idea where to begin looking.
When I run a basic SELECT on two specific tables in our DB:
SELECT * FROM table_name
Using SQL Server Management Studio I get this...
Msg 207, Level 16, State 1, Line 1
Invalid column name 'eventTime'.
There was an eventTime column but wasn’t necessary and wasn't being used in any PHP file, however it seems somehow directly tied to the table now and I have no idea where to look to find it. The error message provided is pointing to my SELECT statement, but there is nothing wrong with it, nor does it even reference the eventTime column.
I’ve looked and there don’t seem to be any triggers or stored procedures referencing this table. Is there another way I can try to track this down?
This sounds like a hard'ish problem. Here are some ideas.
My first thought is that table_name is a view, and somehow the view has gotten out-of-sync with the underlying table definitions. I have seen problems with types in some circumstances. I imagine the same could happen with column names.
The next thought is that table_name has computed columns. In this case, the computed columns could be using a function and the function call could be generating the error. I cannot think of any other way to run code with a simple select.
I don't think the problem would be a foreign key constraint unless. So, a third option is that a foreign key constraint is referencing a table in the same database but a different schema. The different schema could have permissions that make the table inaccessible.
For any of these, scripting out the definition in SSMS will help you fix the problem.

Is there any way to safely run SELECT INTO?

I have a script that runs a SELECT INTO into a table. To my knowledge, there are no other procedures that might be concurrently referencing/modifying this table. Once in awhile, however, I get the following error:
Schema changed after the target table was created. Rerun the Select
Into query.
What can cause this error and how do I avoid it?
I did some googling, and this link suggests that SELECT INTO cannot be used safely without some crazy try-catch-retry logic. Is this really the case?
I'm using SQLServer 2012.
Unless you really don't know the fields and data types in advance, I'd recommend first creating the table, then adding the data with an Insert statement. In your link, David Moutray suggests the same thing, here's his example code verbatim:
CREATE TABLE #TempTableY (ParticipantID INT NOT NULL);
INSERT #TempTableY (ParticipantID)
SELECT ParticipantID
FROM TableX;

How to deal with a Firebird table that's apparently both there and not there

I've just had something very strange happen to me with a Firebird database.
I was trying to create a table, and the CREATE TABLE failed for some reason. But now it's stuck in a very strange state:
If I try to CREATE TABLE again with the same table name, it gives an error: the table already exists. But if I try to DROP TABLE that table, it gives an error: the table does not exist. Trying to SELECT * FROM that table gives the "table does not exist" error, and the name does not show up in the metadata query:
SELECT RDB$RELATION_NAME
FROM RDB$RELATIONS
WHERE RDB$SYSTEM_FLAG=0
So for some reason, the table really seems to not be there, but I can't create it because something somewhere indicates that it does exist.
Does anyone have any idea how to fix this? I've already tried closing all connections to that database, which has helped with inconsistency issues in the past, but this time it doesn't help.
You didn't give details about what was the error when you tried to create the table, so I cannot comment it. But RDB$RELATIONS is not the only system table affected when you create a table. Maybe you are now in an inconsistent situation where some information about that table exists in some system tables and doesn't exists in others.
Another option is corrupted indexes in the system tables, so the record is not there but the index think it still exists.
Try to do a backup/restore and see if it helps. It it doesnt work, try to search for records related to that "non created" table in the other system tables (RDB$RELATION_FIELDS, etc) and if you find any, try to delete them.
As a last option, you may create a new clean database with correct metadata and pump your data to it using IBDataPump.

Debugging sub-queries in TSQL Stored Procedure

How do I debug a complex query with multiple nested sub-queries in SQL Server 2005?
I'm debugging a stored procedure and trigger in Visual Studio 2005. I'd like to be able to see what the results of these sub-queries are, as I feel that this is where the bug is coming from. An example query (slightly redacted) is below:
UPDATE
foo
SET
DateUpdated = ( SELECT TOP 1 inserted.DateUpdated FROM inserted )
...
FROM
tblEP ep
JOIN tblED ed ON ep.EnrollmentID = ed.EnrollmentID
WHERE
ProgramPhaseID = ( SELECT ...)
Visual Studio doesn't seem to offer a way for me to Watch the result of the sub query. Also, if I use a temporary table to store the results (temporary tables are used elsewhere also) I can't view the values stored in that table.
Is there anyway that I can add a watch or in some other way view these sub-queries? I would love it if there was some way to "Step Into" the query itself, but I imagine that wouldn't be possible.
Ok first I would be leary of using subqueries in a trigger. Triggers should be as fast as possible, so get rid of any correlated subqueries which might run row by row instead of in a set-based fashion. Rewrite to joins. If you only want to update records based on what was in the inserted table, then join to it. Also join to the table you are updating. Exactly what are you trying to accomplish with this trigger? It might be easier to give advice if we understood the business rule you are trying to implement.
To debug a trigger this is what I do.
I write a script to:
Do the actual insert to the table
without the trigger on on it
Create a temp table named #inserted
(and/or one named #deleted)
Populate the table as I would expect
the inserted table in the trigger to
be populated from the insert you do.
Add the trigger code (minus the
create or alter trigger parts)
substituting #inserted every time I
reference inserted. (if you plan to
run multiple times until you are
ready to use it in a trigger throw
it in an explicit transaction and
rollback after checking your
results.
Add a query to check the table(s)
you are changing with the trigger for
the values you wanted to change.
Now if you need to add debug
statements to see what is happening
between steps, you can do so.
Run making changes until you get the
results you want.
Once you have the query working as
you expect it to, it is easy to take
the # signs off inserted and use it
to create the body of the trigger.
This is what I usually do in this type of scenerio:
Print out the exact sqls getting generated by each subquery
Then run each of then in the Management Studio as suggested above.
You should check if different parts are giving you the right data you expect.

SQL: How to copy a row in the same table updating one of the fields WITHOUT listing all fields

Hello
I searched for an answer to this question but didn't find any here.
I'm using Access 2010.
Basically, I've got a table with reports, and reports have a revision number.
I found an answer about how to copy fields and update only one of them, but it looks somewhat like this:
INSERT INTO reports (fieldA, fieldB, fieldC, revision, fieldD, fieldE)
SELECT fieldA, fieldB, fieldC, 2, fieldD, fieldE
FROM reports
WHERE <somecondition to select which report to copy>
Thing is I have a load of fields, so I'd like something that would look more like this:
INSERT INTO reports
SELECT *, revision=2
FROM reports
WHERE <somecondition to select which report to copy>
I know that code is incorrect; it's just to describe what I would like. As in, a way to not have a huge SQL line listing all the fields, but only the one I want to change.
(I want to keep a copy of previous revisions in the same table)
Thanks in advance to whoever can help :)
I'm pretty sure you can't do this in MS Access or indeed any other flavor of SQL. What you can do, as you probably already know, is use a stored procedure (called a Stored Query in Access) which takes your revision number and the id of the report to copy (or some other WHERE conditions) as arguments. This way, you still have to specify all the fields, but you do it only once and in your database instead of in your code. An example is here:
http://www.stardeveloper.com/articles/display.html?article=2001050101&page=1
HTH!
I found an interesting alternative in this question, using a temporary table
SQL clone record with a unique index
DROP TABLE #tmp_MyTable
SELECT * INTO #tmp_MyTable
FROM MyTable
WHERE MyIndentID = 165
ALTER TABLE #tmp_MyTable
DROP Column MyIndentID
INSERT INTO MyTable
SELECT *
FROM #tmp_MyTable
I can do the same, dropping the primary key and updating the revision, then copying it back to my table.
Not the solution I'm looking for, but an alternative way in the meantime.
EDIT:
Tried this solution without success:
VBA tells me something along the lines of "fields with multiple values are not allowed with SELECT INTO instructions (runtime error 3838)"
I have both an OLE field and an attachment field, which I suspect to be the cause of the error. But I need to keep them... :/