Drop table, then cannot recreate table with the same name - sql-server-2008

I first drop a table in SQL Server 2008 (after that it shows the message that the command was executed sucessfully).
I then tried to create a table with the same name, and it showed me an error.
After closing the SSMS window and re opening it it tried to create the table with the same name again and it succeeded.
What is going on?

You can't drop and create the same table in the same batch in sql server
see MSDN
Their examples use GO to break up the two commands. Semi colon might work,
Drop Table ...;
Create Table ,,,;
as might
Begin Transaction
Drop Table...
Commit Transaction
Create Table
Or of course splitting it up into two commands, which is what GO does in SQL server manager's query window.
If you do split it up, it might be wise to check whether the table exists before trying to drop it, and that it doesn't before trying to create it.

Related

MYSQL if table exit run something otherwise run another thing [duplicate]

I'm stumped, I don't know how to go about doing this.
Basically I just want to create a table, but if it exists it needs to be dropped and re-created, not truncated, but if it doesn't exist just create it.
Would anyone be able to help?
Just put DROP TABLE IF EXISTS `tablename`; before your CREATE TABLE statement.
That statement drops the table if it exists but will not throw an error if it does not.
Just use DROP TABLE IF EXISTS:
DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );
Try searching the MySQL documentation first if you have any other problems.
Well... Huh. For years nobody mentioned one subtle thing.
Despite DROP TABLE IF EXISTS `bla`; CREATE TABLE `bla` ( ... ); seems reasonable, it leads to a situation when old table is already gone and new one has not been yet created: some client may try to access subject table right at this moment.
The better way is to create brand new table and swap it with an old one (table contents are lost):
CREATE TABLE `bla__new` (id int); /* if not ok: terminate, report error */
RENAME TABLE `bla__new` to `bla`; /* if ok: terminate, report success */
RENAME TABLE `bla` to `bla__old`, `bla__new` to `bla`;
DROP TABLE IF EXISTS `bla__old`;
You should check the result of CREATE ... and do not continue in
case of error, because failure means that other thread didn't finish
the same script: either because it crashed in the middle or just
didn't finish yet -- it's a good idea to inspect things by yourself.
Then, you should check the result of first RENAME ... and do not
continue in case of success: whole operation is successfully
completed; even more, running next RENAME ... can (and will) be
unsafe if another thread has already started same sequence (it's
better to cover this case than not to cover, see locking note below).
Second RENAME ... atomically replaces table definition, refer to
MySQL manual
for details.
At last, DROP ... just cleans up the old table,
obviously.
Wrapping all statements with something like SELECT GET_LOCK('__upgrade', -1); ... DO RELEASE_LOCK('__upgrade'); allows to just invoke all statements sequentially without error checking, but I don't think it's a good idea: complexity increases and locking functions in MySQL aren't safe for statement-based replication.
If the table data should survive table definition upgrade... For general case it's far more complex story about comparing table definitions to find out differences and produce proper ALTER ... statement, which is not always possible automatically, e.g. when columns are renamed.
Side note 1:
You can deal with views using the same approach, in this case CREATE/DROP TABLE merely transforms to CREATE/DROP VIEW while RENAME TABLE remains unchanged. In fact you can even turn table into view and vice versa.
CREATE VIEW `foo__new` as ...; /* if not ok: terminate, report error */
RENAME TABLE `foo__new` to `foo`; /* if ok: terminate, report success */
RENAME TABLE `foo` to `foo__old`, `foo__new` to `foo`;
DROP VIEW IF EXISTS `foo__old`;
Side note 2:
MariaDB users should be happy with CREATE OR REPLACE TABLE/VIEW, which already cares about subject problem and it's fine points.
I needed to drop a table and re-create with a data from a view.
I was creating a table out of a view and this is what I did:
DROP TABLE <table_name>;
CREATE TABLE <table_name> AS SELECT * FROM <view>;
The above worked for me using MySQL MariaDb.

SQL: Drop Column Syntax Error

I want to drop a column from my table. I have tried executing the following syntax:
ALTER TABLE user
DROP COLUMN departmentid;
On execution, it hits me with an error stating that the statement could not be prepared. Can anyone tell me why it's doing this? I get the same error when I try renaming a column.
If you are using MySQL, Try using
DROP departmentid;
Use BackTicks 'column name' in the query.
It might not be possible to DELETE, INSERT or ALTER a table in online query builders. because once you drop tables, others cannot play around with same table. So I dont thing you have privileges to do so. If you are learning install xamp which has installed apache server and MySQL.
Hope this info helps!
I solved the problem by executing below query:
I need to remove a column and all the entries from that column to free my DB size
my initial table structure is as shown below:
CREATE TABLE words(_id,word,synonyms,favorite,history,updDate)
And I wanted the table in below form
CREATE TABLE words(_id,word,favorite,history,updDate)
So I executed below query and it removed "synonyms" column
BEGIN TRANSACTION;
CREATE TEMPORARY TABLE t1_backup(_id,word,favorite,history,updDate);
INSERT INTO t1_backup SELECT _id,word,favorite,history,updDate FROM words;
DROP TABLE words;
CREATE TABLE words(_id,word,favorite,history,updDate);
INSERT INTO words SELECT _id,word,favorite,history,updDate FROM t1_backup;
DROP TABLE t1_backup
COMMIT;

Mysql temp tables are dropped between executions

I want be able to debug easily my scripts in Mysql, like in MSSQL (run a chunk of the script then verify the tables and so on), but the temporary tables are not persisted on the server.
For example :
CREATE temporary table a(i int);
INSERT INTO a VALUE (1);
SELECT * FROM a;
If I run the whole script it returns me the right result, but if I run it statement by statement on the insert I get the following error:
SQL.sql: Error (2,13): Table 'test.a' doesn't exist
I suppose this is a server configuration problem.
Temporary tables are dropped when the transaction is over.
from dev.mysql:
Temporary Tables:
You can use the TEMPORARY keyword when creating a
table. A TEMPORARY table is visible only to the current connection,
and is dropped automatically when the connection is closed. This means
that two different connections can use the same temporary table name
without conflicting with each other or with an existing non-TEMPORARY
table of the same name. (The existing table is hidden until the
temporary table is dropped.) To create temporary tables, you must have
the CREATE TEMPORARY TABLES privilege.
Note CREATE TABLE does not automatically commit the current active
transaction if you use the TEMPORARY keyword.
So if you run all these sql in deferent transactions you temporary table wont exist when you run the insert statement.
If these executions are executed in diferent transactions depend on what interface you use. Thats wy if you "run the whole script it returns me the right result" because its all in the same transaction.
You can try to force it to run on the same transaction with:
START TRANSACTION;
<SQL QUERYS>
COMMIT;
anyway i recomend you MySQL Workbench as interface.
my best regards, i hope this help you.

If table exists drop table then create it, if it does not exist just create it

I'm stumped, I don't know how to go about doing this.
Basically I just want to create a table, but if it exists it needs to be dropped and re-created, not truncated, but if it doesn't exist just create it.
Would anyone be able to help?
Just put DROP TABLE IF EXISTS `tablename`; before your CREATE TABLE statement.
That statement drops the table if it exists but will not throw an error if it does not.
Just use DROP TABLE IF EXISTS:
DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );
Try searching the MySQL documentation first if you have any other problems.
Well... Huh. For years nobody mentioned one subtle thing.
Despite DROP TABLE IF EXISTS `bla`; CREATE TABLE `bla` ( ... ); seems reasonable, it leads to a situation when old table is already gone and new one has not been yet created: some client may try to access subject table right at this moment.
The better way is to create brand new table and swap it with an old one (table contents are lost):
CREATE TABLE `bla__new` (id int); /* if not ok: terminate, report error */
RENAME TABLE `bla__new` to `bla`; /* if ok: terminate, report success */
RENAME TABLE `bla` to `bla__old`, `bla__new` to `bla`;
DROP TABLE IF EXISTS `bla__old`;
You should check the result of CREATE ... and do not continue in
case of error, because failure means that other thread didn't finish
the same script: either because it crashed in the middle or just
didn't finish yet -- it's a good idea to inspect things by yourself.
Then, you should check the result of first RENAME ... and do not
continue in case of success: whole operation is successfully
completed; even more, running next RENAME ... can (and will) be
unsafe if another thread has already started same sequence (it's
better to cover this case than not to cover, see locking note below).
Second RENAME ... atomically replaces table definition, refer to
MySQL manual
for details.
At last, DROP ... just cleans up the old table,
obviously.
Wrapping all statements with something like SELECT GET_LOCK('__upgrade', -1); ... DO RELEASE_LOCK('__upgrade'); allows to just invoke all statements sequentially without error checking, but I don't think it's a good idea: complexity increases and locking functions in MySQL aren't safe for statement-based replication.
If the table data should survive table definition upgrade... For general case it's far more complex story about comparing table definitions to find out differences and produce proper ALTER ... statement, which is not always possible automatically, e.g. when columns are renamed.
Side note 1:
You can deal with views using the same approach, in this case CREATE/DROP TABLE merely transforms to CREATE/DROP VIEW while RENAME TABLE remains unchanged. In fact you can even turn table into view and vice versa.
CREATE VIEW `foo__new` as ...; /* if not ok: terminate, report error */
RENAME TABLE `foo__new` to `foo`; /* if ok: terminate, report success */
RENAME TABLE `foo` to `foo__old`, `foo__new` to `foo`;
DROP VIEW IF EXISTS `foo__old`;
Side note 2:
MariaDB users should be happy with CREATE OR REPLACE TABLE/VIEW, which already cares about subject problem and it's fine points.
I needed to drop a table and re-create with a data from a view.
I was creating a table out of a view and this is what I did:
DROP TABLE <table_name>;
CREATE TABLE <table_name> AS SELECT * FROM <view>;
The above worked for me using MySQL MariaDb.

MySQl Trigger help needed

using MySQL 5.1.36, I am trying to write trigger which drops scratch tables form "scratch" database.
CREATE DEFINER=`root`#`localhost` TRIGGER
`jobq`.`DropScratch`
BEFORE DELETE ON jobq.jobq FOR EACH ROW
BEGIN
DECLARE tblname VARCHAR(128);
set tblname=concat('scratch.',OLD.jobname);
DROP TABLE IF EXISTS tblname;
END;
I am always getting an error:
Explicit or implicit commit is not allowed in stored function or trigger.
Can I somehow overcome this restriction?
Thank you beforehand
Arman
The primary problem here is that you are not allowed to drop a table within a trigger. That's what the error message is getting at when it says "implicit commit" is not allowed. The drop table does an implicit commit.
So you will need to figure out a different way to do this other than a trigger. One way would be to set up a cron job which compares the data in information_schema.tables to the jobq table to look for tables in the scratch DB that can be dropped, and then drop them.
I should also point out that the way you are trying to dynamically create a drop table statement will not work. That is going to drop a table named literally "tblname", not "scratch.jobname". If you want to drop a table dynamically you will need to build the drop table statement in a separate scripting language, such as python, perl, shell, etc.
Good luck!