Drop and create table in one command - sql

do you know why below code is wrong on ms sql server?
DROP TABLE [IF EXISTS] database.table1,
create table table1 (...)

That's SQL Server 2016 syntax.
For earlier versions, you can use the EXISTS function to check whether your table exists in the sys.tables list and drop it if it does. Then create a new table.
Somewhat like this:
IF EXISTS (SELECT * FROM sys.tables WHERE name = 'table1' AND type = 'U') DROP TABLE table1;
CREATE TABLE table1
(
...
...
);

This syntax is only valid on SQL Server 2016, which is not released yet.
Are you sure that you are using that version?
Otherwise you could use the IF Exists that #pradeep-kumar suggests.

Related

How to copy a table from a linked server into the main database only on the condition that the table does not already exist?

I am using SQL Server 2012 and I have the following T-SQL query:
USE MyDatabase
INSERT INTO [Table1]
SELECT *
FROM [xxx.xx.x.xx].[xxx].[dbo].[Table1]
I would like to modify this query so that it copies Table1 into MyDatabase only if that table does not already exist in MyDatabase.
I've had a look here but I can't figure out how to migrate the solutions into my problem: Check if table exists in SQL Server
How can I achieve this?
This should do it:
IF (NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Table1'))
BEGIN
INSERT INTO [Table1]
SELECT *
FROM [xxx.xx.x.xx].[xxx].[dbo].[Table1]
END
More details and approaches you can read here:
Check if table exists in SQL Server

There is already an object named '#DIR_Cat' in the database

In my Stored procedure, I have added a command to create a hash temp table #DIR_CAT. But every time I execute the procedure I get this error:
"There is already an object named '#DIR_Cat' in the database."
Even when I have already created an Exists clause at the start of SP to check and drop the table if it is present. Any help is much appreciated.
The code goes like this.
if exists (select * from dbo.sysobjects where id = object_id(N'#DIR_Cat') )
drop table #DIR_Cat
/* some lines of code*/
CREATE TABLE #DIR_Cat (XMLDta xml)
/* some lines of code*/
INSERT #DIR_Cat exec (#stmt)
/* some lines of code*/
drop table #DIR_Cat
Main issue is you're not fully qualifying your objects. Your temp table lives in tempdb, whereas the system views use whatever database you're currently connected to by default. So essentially you're looking for the temp table, but you're looking in whatever database your currently connected to (which I'm guessing is not tempdb).
I'm assuming you're using SQL Server here, although you did also mention mysql in the tags. If that's what you're using, this code may not apply.
Here's the snippet I use for temp table drop/create
if object_id('tempdb.dbo.#<TableName, sysname, >') is not null drop table #<TableName, sysname, >
create table #<TableName, sysname, >
(
)
Side note, don't use dbo.sysobjects. That's a really old compatibility view. If you want to use objects, use sys.objects instead.
temp table does not exists in local DB sys.objects, it is in tempdb
you need to query tempb.sys.objects
the name of the temp table does not appear exactly as it is in the tempdb.sys.objects.
You can't query it just like
select *
from tempdb.sys.objects
where name = '#DIR_Cat' -- This does not works
you need to use object_id()
select *
from tempdb.sys.objects
where object_id = object_id('tempdb..#DIR_Cat')

Drop view if exists

I have script where I want to first drop view and then create it.
I know how to drop table:
IF EXISTS (SELECT * FROM sys.tables WHERE name = 'table1' AND type = 'U') DROP TABLE table1;
so I did the same for views:
IF EXISTS (SELECT * FROM sys.views WHERE name = 'view1' AND type = 'U') DROP VIEW view1;
create view1 as(......)
and then I got error:
'CREATE VIEW' must be the first statement in a query batch.
your exists syntax is wrong and you should seperate DDL with go like below
if exists(select 1 from sys.views where name='tst' and type='v')
drop view tst;
go
create view tst
as
select * from test
you also can check existence test, with object_id like below
if object_id('tst','v') is not null
drop view tst;
go
create view tst
as
select * from test
In SQL 2016,you can use below syntax to drop
Drop view if exists dbo.tst
From SQL2016 CU1,you can do below
create or alter view vwTest
as
select 1 as col;
go
Regarding the error
'CREATE VIEW' must be the first statement in a query batch.
Microsoft SQL Server has a quirky reqirement that CREATE VIEW be the only statement in a batch. This is also true of a few other statements, such as CREATE FUNCTION. It is not true of CREATE TABLE, so go figure …
The solution is to send your script to the server in small batches. One way to do this is to select a single statement and execute it. This is clearly inconvenient.
The more convenient solution is to get the client to send the script in small isolated batches.
The GO keyword is not strictly an SQL command, which is why you can’t end it with a semicolon like real SQL commands. Instead it is an instruction to the client to break the script at this point and to send the portion as a batch.
As a result, you end up writing something like:
DROP VIEW IF EXISTS … ;
GO
CREATE VIEW … AS … ;
GO
None of the other database servers I have encountered (PostgreSQL, MySQL, Oracle, SQLite) have this quirk, so the requirement appears to be Microsoft Only.
DROP VIEW if exists {ViewName}
Go
CREATE View {ViewName} AS
SELECT * from {TableName}
Go
To cater for the schema as well, use this format in SQL 2014
if exists(select 1 from sys.views V inner join sys.[schemas] S on v.schema_id = s.schema_id where s.name='dbo' and v.name = 'someviewname' and v.type = 'v')
drop view [dbo].[someviewname];
go
And just throwing it out there, to do stored procedures, because I needed that too:
if exists(select 1
from sys.procedures p
inner join sys.[schemas] S on p.schema_id = s.schema_id
where
s.name='dbo' and p.name = 'someprocname'
and p.type in ('p', 'pc')
drop procedure [dbo].[someprocname];
go

drop table #temp vs drop myTable if it's not null

So far i was using
IF OBJECT_ID(''tempdb..#tempTable'') IS NOT NULL -- dropping the temp table
DROP TABLE #tempTable
Is there a way in which I could use the same statement for a table which is not a temp one?
Tried like this and it didn't work:
IF OBJECT_ID(''myOwnDb.dbo.myTable'') IS NOT NULL -- dropping the table
DROP TABLE dbo.myTable
Strings in MS SQL server should be enclosed in single quotes.
So neither OBJECT_ID(''myOwnDb.dbo.myTable'') nor OBJECT_ID("myOwnDb.dbo.myTable") will work.
But OBJECT_ID('myOwnDb.dbo.myTable') will work perfectly.
In addition to what other users have suggested wrt Object_ID which is fine, you can explore below method to detect if table exist or not using INFORMATION_SCHEMA
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = N'Your Table Name')
BEGIN
Drop table <tablename>
END
The reason it did not work is because you have the extra quotes instead of single quotes.
i.e. You should be doing this:
IF OBJECT_ID('myOwnDb.dbo.myTable') IS NOT NULL -- dropping the table
DROP TABLE dbo.myTable
However, note that when you actually drop the table. You aren't even referencing the database. So you can just do:
IF OBJECT_ID('dbo.myTable') IS NOT NULL -- dropping the table
DROP TABLE dbo.myTable
Unless you are calling this command from another database. Then you will need to include the database name in the DROP TABLE command as well.

How to drop a table in SQL Server 2008 only if exists

Our company is migrating one of its products from SQL Server 2005 to 2008, and in the logs I've noticed excess of errors about deleting tables if it does not exist. In SQL Server 2005 we had this to delete tables
IF OBJECT_ID('dbo.Units', 'U') IS NOT NULL
DROP TABLE dbo.Units
which doesn't seem to work anymore.
What would be the proper way of deleting a table only if it exists in SQL Server 2008?
This should do it!
IF EXISTS
(SELECT
TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TableToDrop')
DROP TABLE TableToDrop
This code works on my SQL Server 2012:
IF OBJECT_ID('t', 'U') IS NOT NULL DROP TABLE t
CREATE TABLE t(id int)
Maybe your name is wrong (e.g. case sensitive collation on new installation?). What kind of error you are getting?
Note that in SQL Server 2016 you can use DROP IF EXISTS:
DROP TABLE IF EXISTS t
CREATE TABLE t(id int)