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
Related
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
When I execute
exec sp_columns TABLE_NAME
it returns many columns, I need to display specific columns only and add a description column as well.
Is there anyway for me to customize the table to do this?
I am using SQL Server 2012 Management Studio
With SSMS you can use the table designer to add columns fairly easily. In the server browser, find your table, right click, and "Design."
--Check if column does not exists, if yes than add.
IF NOT EXISTS (
SELECT *
FROM sys.columns
WHERE [name] = N'Column_Name'
AND [object_id] = OBJECT_ID(N'Table_Name')
)
BEGIN
ALTER TABLE Table_Name ADD Column_Name Type;
END
-- Similarly for removing column
--Check if column does exists, if yes than add.
IF EXISTS (
SELECT *
FROM sys.columns
WHERE [name] = N'Column_Name'
AND [object_id] = OBJECT_ID(N'Table_Name')
)
BEGIN
ALTER TABLE Table_Name Remove Column_Name;
END
GO
select column_name, table_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME like '%table name%' and column_name
in
(
'column1',
'column2'
)
I have database with table 'Product', column 'Name'. I need to implement case and accent insensitive search so I tried to change collation of the column like this:
EXEC sp_fulltext_column #tabname = 'Product' , #colname = 'Name', #action = 'drop'
ALTER TABLE dbo.Product
ALTER COLUMN Name nvarchar(400) COLLATE SQL_Latin1_General_CP1_CI_AI NOT NULL;
EXEC sp_fulltext_column #tabname = 'Product' , #colname = 'Name', #action = 'add'
Then I checked the collation of the column like this:
SELECT collation_name FROM sys.columns
WHERE name = 'name' AND object_id = (select object_id from sys.tables where name = 'Product');
And collation is set correctly to CI and AI (SQL_Latin1_General_CP1_CI_AI).
I have test products in database with names like 'Čučoriedka', 'Čúčo', 'Test'.
I would like to be able select 'Čučoriedka' and 'Čúčo' by query:
select * from product where CONTAINS([Name], 'cuc')
But neither 'test' is working with this queries:
select * from product where CONTAINS([Name], 'tes')
select * from product where PATINDEX('tes', [Name] COLLATE SQL_Latin1_General_CP1_CI_AI ) > 0
I tried also another collations, but nothing works.
Do you have any idea what can help here?
Thanks a lot! Marek
I found the solution! I found out that, collation has impact only for ordering. I'm using fulltext search so I need to change fulltext indexes. Here is how I did if anyone else need do the same..
IF EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id('Product'))
DROP FULLTEXT INDEX ON [Product]
DECLARE #create_index_text nvarchar(4000)
SET #create_index_text = '
IF NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(''[Product]''))
ALTER FULLTEXT INDEX ON [Product]([Name] Language 1051, [ShortDescription] Language 1051, [FullDescription] Language 1051, [Sku] Language 1051)
KEY INDEX [' + dbo.[nop_getprimarykey_indexname] ('Product') + '] ON [nopCommerceFullTextCatalog] WITH CHANGE_TRACKING AUTO'
EXEC(#create_index_text)
ALTER FULLTEXT CATALOG nopCommerceFullTextCatalog REBUILD WITH ACCENT_SENSITIVITY=OFF;
The language code 1051 is for slovak language, you can find your code here: http://technet.microsoft.com/en-us/library/ms176076.aspx
Hope it helps!
I am using SQL server 2008. I need to find if default value constraint does not exist then create it. Here is what I have tried.
IF (NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME ='MyConstraint'))
BEGIN
ALTER TABLE [XX] ADD CONSTRAINT [MyConstraint] DEFAULT ((-1)) FOR [XXXX]
END
GO
if not exists (
select *
from sys.all_columns c
join sys.tables t on t.object_id = c.object_id
join sys.schemas s on s.schema_id = t.schema_id
join sys.default_constraints d on c.default_object_id = d.object_id
where t.name = 'table'
and c.name = 'column'
and s.name = 'schema')
....
I find this to be easier:
IF OBJECT_ID('SchemaName.MyConstraint', 'D') IS NULL
BEGIN
-- create it here
END
I was a bit puzzled as to why this simple task was so complicated. In my case, I don't have constraint names - only table and column names. I want to check if they already have a default before trying to add one.
After a bit more digging, I came up with this:
IF (SELECT Column_Default FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MY_TABLE' AND COLUMN_NAME = 'MY_COLUMN') is NULL
BEGIN
ALTER TABLE [dbo].[MY_TABLE]
ADD DEFAULT ('') FOR [MY_COLUMN]
END
GO
I have to implement this in a ginormous boilerplate script, so the shorter the better.
if not exists(select 1 from sys.default_constraints where name = 'SchemaName.MyConstraint')
begin
-- create it here
end
The following works for me on SQL Server 2016.
Assuming I have a table named MY_TABLE and a column MY_COLIUMN.
I would like to add a constrain (default to '-1' ) on MY_COLIUMN that need to add the constrain on.
/* Test for the specific column */
IF EXISTS (select 1 from sys.all_columns c where c.object_id= OBJECT_ID(N'MY_TABLE') and c.name='MY_COLIUMN')
BEGIN
/* Add default if not exits */
IF NOT EXISTS (
select 1 from sys.default_constraints c where c.object_id =
(
select default_object_id from sys.all_columns c where c.object_id = OBJECT_ID(N'MY_TABLE') and c.name='MY_COLIUMN'
)
)
BEGIN
ALTER TABLE MY_TABLE
ADD DEFAULT '-1' FOR MY_COLIUMN;
END
END
GO
I've used the following in the past:
DECLARE #default sysname
SELECT #default = object_name( cdefault ) FROM syscolumns WHERE id = object_id( 'DBO.TABLE' ) AND name = 'COLUMN'
IF ( not #default is null )
BEGIN
...
END
Search the system table where the default costraints of the database are stored, without the schema name:
IF EXISTS(SELECT 1 FROM sys.default_constraints WHERE [name] = 'MyConstraint')
print 'Costraint exists!';
ELSE
print 'Costraint doesn''t exist!';
I know I'm coming to the party late here, but I am a big fan of OBJECTPROPERTY. Here is how to set a default of 1 on a column if the default does not yet exist.
IF (OBJECTPROPERTY(OBJECT_ID('My_constraint_name'),'CnstIsColumn') IS NULL
ALTER TABLE Mytable ADD CONSTRAINT [MY_constraint_name] DEFAULT ((1)) FOR [My_column_name]
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