SQL Server: the following stored procedure is not working, but the SQL statement works outside of stored procedure.
CREATE PROCEDURE schema1.dropConstraints
(@schemaName AS nvarchar, @tableName AS nvarchar)
AS
BEGIN
DECLARE @cname nvarchar(80)
DECLARE @sqlStatement nvarchar(100)
DECLARE myCursor CURSOR LOCAL FOR
SELECT constraint_name
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE constraint_schema = @schemaName
AND table_name = @tableName;
OPEN myCursor;
FETCH NEXT FROM myCursor INTO @cname;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sqlStatement = 'ALTER TABLE ' + @schemaName + '.' + @tableName + ' DROP CONSTRAINT ' + @cname;
EXEC sp_executesql @sqlStatement;
FETCH NEXT FROM myCursor INTO @cname;
END;
CLOSE myCursor;
DEALLOCATE myCursor;
END;
Calling stored procedure
exec schema1.dropConstraints 'schema1', 'Foo';
Table Foo
's constraints (PK, FK) were not removed. No errors.
But running the code outside stored procedure, it works fine.
DECLARE @schemaName nvarchar(80) = 'schema1';
DECLARE @tableName nvarchar(80) = 'Foo';
DECLARE @cname nvarchar(80)
DECLARE @sqlStatement nvarchar(100)
DECLARE myCursor CURSOR LOCAL FOR
SELECT constraint_name
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE constraint_schema = @schemaName AND table_name = @tableName;
OPEN myCursor;
FETCH NEXT FROM myCursor INTO @cname;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sqlStatement = 'ALTER TABLE ' + @schemaName + '.' + @tableName + ' DROP CONSTRAINT ' + @cname;
EXEC sp_executesql @sqlStatement;
FETCH NEXT FROM myCursor INTO @cname;
END;
CLOSE myCursor;
DEALLOCATE myCursor;
This works. Table Foo
's constraints (PK, FK) were removed. What is the difference?
login: sa.