I am trying to drop pk constraint and drop index on the target table in informatica, these below statements are working first time successfully.
IF EXISTS (SELECT Name FROM sysindexes WHERE Name = 'xyz')
DROP INDEX [xyz] ON [dbo].[Table_Name];
IF EXISTS (SELECT Name FROM sysindexes WHERE Name = 'xyz')
ALTER TABLE [dbo].[Table_Name] DROP CONSTRAINT [xyz];
But if I run the same query a second time it is giving an error:
Cannot drop the index 'dbo.Table_Name.xyz', because it does not exist or you do not have permission
I need an If ... Else statement syntax like if exists drop else end or success something.
The likely cause for this is that you might have more than one index named xyz on your database. Your IF EXISTS SELECT statement is not taking into consideration which table xyz is on.
You can check for this condition yourself by running the select statement by itself.
Try changing your query to the following to limit the scope:
If Exists
(
Select *
From sys.indexes
Where name = 'xyz'
And Object_Id = Object_Id('dbo.Table_Name')
)
Drop Index xyz On dbo.Table_Name;
One way to get around this issue is to trick the parser:
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE SCHEMA_NAME = 'dbo' AND TABLE_NAME = 'Table_Name' AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME = 'xyz')
BEGIN
EXEC('ALTER TABLE [dbo].[Table_Name] DROP CONSTRAINT [xyz]')
END
Related
I got a pretty complex SQL that finally forced me to use a temp table to work around.
Essentially it looks like this:
;IF EXISTS(SELECT * FROM sys.tables WHERE SCHEMA_NAME(schema_id) LIKE 'dbo' AND name like '#MYTEMPTABLE')
DROP TABLE #MYTEMPTEBLE;
WITH cte AS ...
SELECT * INTO #MYTEMPTABLE FROM cte
SELECT * FROM #MYTEMPTABLE WHERE [conditions]
DROP TABLE #MYTEMPTABLE;
However, I get an error message saying an object with the name #MYTEMPTABLE already exists in the database after a call with an error (which is rather likely if the customer/tester screws up some data).
It might DROP TABLE fail on your check condition, it might check from TempDB.INFORMATION_SCHEMA.COLUMNS table instead of sys.tables table
SELECT * FROM TempDB.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME IN (
SELECT NAME
FROM TempDB.SYS.TABLES
WHERE OBJECT_ID=OBJECT_ID('TempDB.dbo.#MYTEMPTEBLE')
);
sqlfiddle
If your SQL server version was higher than 2016, you can try to use DROP TABLE IF EXISTS
DROP TABLE IF EXISTS #MYTEMPTEBLE;
WITH cte AS ...
SELECT * INTO #MYTEMPTABLE FROM cte
SELECT * FROM #MYTEMPTABLE WHERE [conditions]
if your SQL server version didn't support that, you can check OBJECT_ID IS NOT NULL which represnt temp table exists in your system
IF OBJECT_ID('TempDB..#MYTEMPTEBLE') IS NOT NULL
DROP TABLE #MYTEMPTEBLE;
I try to use script to add column to table, no matter i change to which name, it always return error saying
Column names in each table must be unique. Column name 'xxx' in table
'TEST_TABLE' is specified more than once.
I randomly key in a name, it still saying that name is specified more than once. but actually not, there is no such column existed yet, and column finally is not added successfully also.
anyone had any idea?
thanks
below is my query:
GO
if not exists(SELECT * FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'TEST_TABLE' AND COLUMN_NAME = 'EP_TEXT')
begin
ALTER TABLE TEST_TABLE ADD EP_TEXT [dbo].[UDDT_MAXVARCHAR] NULL
end
GO
The problem is that INFORMATION_SCHEMA.TABLE does not have a COLUMN_NAME column. Try this:
IF NOT EXISTS(
SELECT * from INFORMATION_SCHEMA.TABLES t1
INNER JOIN INFORMATION_SCHEMA.COLUMNS t2 on t1.TABLE_NAME = t2.TABLE_NAME
where t1.TABLE_NAME = 'TEST_TABLE' and t2.COLUMN_NAME = 'EP_TEXT'
)
I am first checking if column exist or not. If not then i rename existing column and then try to change its datatype. But when i run script i get error Invalid column name Age
if Not exists(select * from sys.columns
where Name = 'Age' and Object_ID = Object_ID('TestTable'))
begin
EXEC sp_RENAME 'TestTable.Name' , 'Age', 'COLUMN'
ALTER TABLE TestTable ALTER COLUMN Age int
Update TestTable set Age = 0
ALTER TABLE TestTable ALTER COLUMN Age int Not Null
end
What am i doing wrong here?
Try this. By splitting your If condition with Not Exists and exists.
if Not exists(select * from sys.columns
where Name = 'Age' and Object_ID = Object_ID('TestTable'))
BEGIN
EXEC sp_RENAME 'TestTable.Name' , 'Age', 'COLUMN'
END
GO
if exists(select * from sys.columns
where Name = 'Age' and Object_ID = Object_ID('TestTable'))
begin
ALTER TABLE TestTable ALTER COLUMN Age int
Update TestTable set Age = 0
ALTER TABLE TestTable ALTER COLUMN Age int Not Null
END
GO
Edit:
About Batch in SQL from here
A table cannot be changed and then the new columns referenced in the
same batch.
So, renaming and altering in the same batch not worked.
See here
When an error occurs while executing a batch of SQL statements,
No statements in the batch are executed.
This question already has answers here:
How to check if a Constraint exists in Sql server?
(15 answers)
Closed 9 years ago.
I have the following:
IF OBJECT_ID(N'[dbo].[webpages_Roles_UserProfiles_Target]', 'xxxxx') IS NOT NULL
DROP CONSTRAINT [dbo].[webpages_Roles_UserProfiles_Target]
I want to be able to check if there is a constraint existing before I drop it. I use the code above with a type of 'U' for tables.
How could I modify the code above (change the xxxx) to make it check for the existence of the constraint ?
SELECT
*
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
or else try this
SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
type_desc AS ConstraintType
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT'
or
IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.TableName'))
BEGIN
ALTER TABLE TableName DROP CONSTRAINT CONSTRAINTNAME
END
Try something like this
IF OBJECTPROPERTY(OBJECT_ID('constraint_name'), 'IsConstraint') = 1
ALTER TABLE table_name DROP CONSTRAINT constraint_name
you can do something like :
IF EXISTS
(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CONSTRAINT_NAME]')
AND type in (N'U'))
BEGIN
....
END
ELSE
I use this command to drop a table in sql-server 2008
IF EXISTS(SELECT name FROM [DBName]..sysobjects WHERE name = N'TableName' AND xtype='U')
DROP TABLE [DBName].[SchemaName].[TableName];
But now I have 2 tables with same name in different schema:
[DBName].[Schema1].[Members]
And
[DBName].[Schema2].[Members]
So, what is your suggestion for check if exist this tables? How can I check table names with schema?
UPDATE:
OK, there is 3 different answers and all of them worked, so I don't know which one is better, does any one know about use object_id or sys.tables?
IF EXISTS(
SELECT *
FROM [DBName].sys.tables t
JOIN [DBName].sys.schemas s
ON t.SCHEMA_ID = s.schema_id
WHERE
t.name = N'TableName' AND t.type='U'
AND s.NAME = 'SchemaName'
)
DROP TABLE [DBName].[SchemaName].[TableName];
Update:
object_id in sys.tables is the same as object_id in sysobjects for the same table. And is completely the same as function OBJECT_ID returns for the same table name. See the following illustrating examples.
So, you may simplify the query:
IF exists
(
SELECT *
FROM DBName.sys.tables
WHERE object_id = OBJECT_ID('[DBName].[SchemaName].[TableName]')
AND type = 'U'
)
DROP TABLE [DBName].[SchemaName].[TableName];
or in this way:
IF exists
(
SELECT *
FROM DBName.sys.objects
WHERE object_id = OBJECT_ID('[DBName].[SchemaName].[TableName]')
AND type = 'U'
)
DROP TABLE [DBName].[SchemaName].[TableName];
or for sql2000-styled tables:
IF exists
(
SELECT *
FROM DBName..sysobjects
WHERE object_id = OBJECT_ID('[DBName].[SchemaName].[TableName]')
AND xtype = 'U'
)
DROP TABLE [DBName].[SchemaName].[TableName];
Use this:
IF EXISTS
(
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[DBName].[Schema1].[Member]')
AND type in (N'U')
)
PRINT 'Yes'
ELSE
PRINT 'No';
Don't use sysobjects. Use the modern system views in the sys schema (introduced in 2005):
select * from sys.tables
where
schema_id = SCHEMA_ID('Schema1') and
name='tablename'
As soon as you have one "modern" schema in a 2005 or later database, you cannot reliably use sysobjects to match with schemas. If you only have "old" schemas (objects belonging to users and roles), you may be able to query based on user_id.
Wouldn't it be simplest just to:
IF object_id('[schema].[table]') > 0
DROP TABLE [schema].[table]
For non existent tables object_id() returns NULL
For some system tables it returns a negative int