Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Cursor to delete foreign keys

Author  Topic 

EDawg
Starting Member

1 Post

Posted - 2015-03-14 : 15:15:22
Hello,
I have two issues with the following code. 1) I don't think it is dropping all foreign keys which its suppose to from sysobjects.(The code runs without any errors) 2) the print function is not working. I would appreciate some guidance on finding out what my issue is. I'm sure its something simple. Thanks for taking a look.


GO
CREATE PROCEDURE uspDropUserForeignKeys

AS

SET NOCOUNT ON
DECLARE @strMessage VARCHAR(250)
DECLARE @strForeignKey VARCHAR(250)
DECLARE @strChildTable VARCHAR(250)
DECLARE @strCommand VARCHAR(250)
DECLARE @strTab CHAR = CHAR(9)

---------------------Drop all user foreign keys------------------------

PRINT @strTab + 'DROP ALL USER FOREIGN KEYS ...'

DECLARE crsForeignKeys CURSOR FOR
SELECT
name AS strForeignKey
,OBJECT_NAME(parent_obj) AS strChildTable
FROM
sysobjects

WHERE
xtype='F' /* Foreign Keys Only */
AND (
name LIKE '%_FK'
OR name LIKE '%_FK_'
)
AND OBJECT_NAME(parent_obj) LIKE 'T%'

ORDER BY
name

OPEN crsForeignKeys
FETCH NEXT FROM crsForeignKeys INTO @strForeignKey, @strChildTable


-- Loop until no more records
WHILE @@FETCH_STATUS = 0
BEGIN

SELECT @strMessage = @strTab + @strTab + '—DROP ' + @strForeignKey
PRINT @strMessage


-- Build command
SELECT @strCommand = 'ALTER TABLE' + @strChildTable + 'DROP CONSTRAINT' + @strForeignKey

-- Execute command
EXECUTE(@strCommand)

FETCH NEXT FROM crsForeignKeys INTO @strForeignKey, @strChildTable

END

-- Clean up
CLOSE crsForeignKeys
DEALLOCATE crsForeignKeys

PRINT @strTab + 'DONE'
GO


Eric Lynch
   

- Advertisement -