I am trying to make a stored procedure to clean constraints from a table.
I have some trouble checking is the is null or empty, also to check is the table exist is there a way more elegant than nest a if to check if the table exists and the parameter isn’t null or empty?
This is for SQL Server 2008 R2.
ALTER PROCEDURE [dbo].[sp_quitarConstrain](@table NVARCHAR(50))
AS
DECLARE @database NVARCHAR(50)
DECLARE @sql NVARCHAR(255)
SET @database = 'table'
IF((COALESCE(@table,'') <> '') OR (@table IS NULL))
BEGIN
PRINT 'Necesitas dar una tabla valida'
RETURN
END
ELSE
BEGIN
WHILE EXISTS(SELECT * FROM sys.foreign_keys WHERE referenced_object_id = object_id(+ @table))
BEGIN
SELECT @sql = 'ALTER TABLE ' + OBJECT_NAME(parent_object_id) + ' DROP CONSTRAINT ' + name
FROM sys.foreign_keys
WHERE referenced_object_id = object_id(@table)
EXEC sp_executesql @sql
END
END
Your Stored Proc does work, with only minor changes – e.g.
(COALESCE(@table,'') <> '')should be(COALESCE(@table,'') = '')If you aren’t too picky about schemas, you could check for the table like so: