Cannot delete primary key constraint in SQL Server - sql-server

When I open designer for a table in SSMS, first column Id has a primary key assigned to it (IDENTITY), and key icon is shown next to it. In the Indexes / Keys window I can see a PK_dbo.Lines entry with Name [PK_dbo.Lines] and type Primary Key.
ALTER TABLE dbo.Lines DROP CONSTRAINT [PK_dbo.Lines]
returns
Msg 3728, Level 16, State 1, Line 33
'PK_dbo.Lines' is not a constraint.
If I execute
SELECT *
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
I can see primary keys for all tables, except for table Lines...
This query also does not return any results:
select object_name (parent_obj) ObjectName, name
from sysobjects
where xtype = 'PK'
and parent_obj = (object_id('[dbo].[Lines]'))
Any idea what is going on here?

If you make any changes to tables / columns in a database SSMS needs to be manually refreshed in order to correctly reflect these changes. Could it be that it is as simple as right-clicking on Tables and select refresh?
Alternatively, you might have spelled the PK name incorrectly? Please try the following script to remove the PK from the table 'Lines':
declare #PK_Name nvarchar(200);
declare #strSQL nvarchar(max);
select #PK_Name = (
select i.name as IndexName
from sys.indexes as i
inner join sys.index_columns as ic
on i.object_id = ic.object_id
and i.index_id = ic.index_id
inner join sys.tables as t
on t.object_id = i.object_id
where i.is_primary_key = 1
and t.name = N'Lines'
)
set #strSQL = N'ALTER TABLE dbo.Lines DROP CONSTRAINT ' + #PK_Name
execute(#strSQL)
First the script retrieves the correct name for the PK and then it tries to drop the PK constraint.

Related

SQL Server : drop default constraint, alter column and recreate constraint

Is it possible and how to alter column with default constraint ?
The problem: I want to invoke this alter:
For example
ALTER TABLE MY_TABLE
ALTER COLUMN MY_COLUMN nvarchar(1024); --(was varchar)
But this code throws an exception:
[S0001][5074] Line 1: The object 'DF__MY_TABLE __MY_COL__2A563856' is dependent on column 'MY_COLUMN '.
I know how to search for that constraint:
select c.name, col.name
from sys.default_constraints c
inner join sys.columns col on col.default_object_id = c.object_id
inner join sys.objects o on o.object_id = c.parent_object_id
inner join sys.schemas s on s.schema_id = o.schema_id
where o.name = 'MY_TABLE' and col.name = 'MY_COLUMN'
and now I not only want to drop the constraint that blocks the execution of the above alter but also recreate this constraint.
I have 100 columns like that so I want to write some procedure or function and call it 100 times in script for each table and command separately.
Moreover some columns would have default values like '' or '-' or no default value at all. It is important that after scripts execution all constraints would be as before execution and none of them would be missing.

SQL Server Renaming Tables

I'm switching contents of my tables by renaming them so the latest data goes to the main table. Does it automatically include the indexes on both tables as well?
EXEC sp_rename 'MAIN', 'TMP';
EXEC sp_rename 'LATEST', 'MAIN';
EXEC sp_rename 'TMP', 'LATEST';
Thanks!
Every table has an object_id and the name it is known by is just an attribute of that object. You could see each of the tables from your question listed in the sys.objects view with a query like this:
select *
from db_nm.sys.objects as o
where o.name in ('MAIN', 'TMP', 'LATEST')
and o.type = 'U' --filtering to (user-defined) Tables only
Each index, listed in the sys.indexes view, shows two IDs. The first is the index_id which is the ID of the index itself, and the object_id which is the ID of the object being indexed.
This means that when you use sp_rename to change the name of the table, the only thing that happens is the name attribute of the object is updated, and none of the ID numbers are being changed.
In other words, if index_a was pointing to object 123456 before renaming the table, it will still point to that object afterwards.
Update:
You can verify the table / index setup by using the query below which will return one record for each table / index combination.
select s.name as schema_nm
, o.name as table_nm
, i.name as index_nm
from db_nm.sys.objects as o
inner join db_nm.sys.schemas as s on o.schema_id = s.schema_id
left join db_nm.sys.indexes as i on o.object_id = i.object_id
where o.type = 'U'
and o.name in ('MAIN', 'TMP', 'LATEST')
order by 1, 2, 3

How can I get the list of no foreign key constraint?

I can get the list of foreign key constraints with a given table name by using
EXEC sp_fkeys 'TableName'
But I need to get the list of all tables which have no foreign key constraints to other tables.
Thanks in advance.
This query below gives you all tables that don't have a Foreign Key
SELECT s.name [Schema], t.name [Table]
FROM sys.tables AS t
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
WHERE NOT EXISTS (SELECT
1
FROM sys.foreign_keys AS fk
WHERE fk.parent_object_id = t.[object_id]);
This logic is inspired from a set of related queries posted at this site.
Here is another option using EXCEPT.
select name
from sys.tables
except
(
select OBJECT_NAME(parent_object_id)
from sys.foreign_keys
)
order by name

SQL Server 2012: Constraint has NULL for name. How can I drop this?

I am not sure how this happened, but I have a PRIMARY KEY constraint on one of my tables and the name is NULL. I discovered it because I had to drop/recreate the table, and when I tried to add the PRIMARY KEY, the system responded that the constraint already existed.
I executed the following:
SELECT i.object_id, i.name, i.type_desc
FROM sys.indexes i
INNER JOIN sys.tables t ON i.object_id = t.object_id
AND t.name = N'Organization'
and the result is:
object_id name type_desc
1570377655 NULL HEAP
1570377655 IX_Organization_OwnedByOrganizationId NONCLUSTERED
I tried dropping and recreating the table several times and each time the index is there. How can I drop the constraint?
You can try to find the index you are trying to add using the following query:
SELECT [Table] = t.[name]
, [Index] = i.[name]
, i.*
FROM sys.indexes i
INNER JOIN sys.tables t
ON t.[object_id] = i.[object_id]
Martin has the right answer to index you find with the NULL name.

Find all foreign key of a table that prevent insert into it in SQL Server

I have a database with about 200 tables with many foreign keys constraints. There is no data in the database and I need to insert rows into a specified table X.
Because of the many foreign keys I don't know the order of how to insert in other tables so that I can insert into table X. Some of foreign key constraint are hierarchical.
How can I find out the order of inserting so that I can successfully insert data into table X? Is there any SQL query that help me?
Edited
I want result in a table with column "TableName" ,"ParentTableDependece" that show tree view and can get select from it
Using this snippet, you can find all other tables and the foreign keys involved that reference your own table X:
;WITH ReferencingFK AS
(
SELECT
fk.Name AS 'FKName',
OBJECT_NAME(fk.parent_object_id) 'ParentTable',
cpa.name 'ParentColumnName',
OBJECT_NAME(fk.referenced_object_id) 'ReferencedTable',
cref.name 'ReferencedColumnName'
FROM
sys.foreign_keys fk
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.columns cpa ON fkc.parent_object_id = cpa.object_id AND fkc.parent_column_id = cpa.column_id
INNER JOIN
sys.columns cref ON fkc.referenced_object_id = cref.object_id AND fkc.referenced_column_id = cref.column_id
)
SELECT
FKName,
ParentTable,
ParentColumnName,
ReferencedTable,
ReferencedColumnName
FROM
ReferencingFK
WHERE
ReferencedTable = 'X' -- <=== put your table name here!
ORDER BY
ParentTable, ReferencedTable, FKName
Once you have all the tables that reference X, you might also need to repeat this for other tables (if they in turn depend on foreign key references)
Why not this?
EXEC sp_msdependencies #objname = 'X'
Raj
You can try:
EXEC sp_help 'TableName'
This will give you the whole details of the table i.e you can get the relations, indexes and other information related with the object you pass with it.

Resources