How do I switch off SCHEMABINDING for a view without recreating it?
Yes. It's good that you use SCHEMABINDING (we do always) and sometimes you have to remove it to change a dependent object. Just ALTER the view
ALTER VIEW myView
--Remove this WITH SCHEMABINDING
AS
SELECT ...
GO
Won't ALTER VIEW allow for you to get this done? When you create a view you would do:
CREATE VIEW
WITH SCHEMABINDING
AS
SELECT stmt
GO
so, lose the WITH clause:
ALTER VIEW viewname
AS
SELECT stmt
GO
See ALTER VIEW on MSDN
After looking around for hours, I created 2 stored proc for this. Hope this helps someone
CREATE PROCEDURE ViewRemoveSchemaBinding
@ViewName VARCHAR(MAX)
AS
BEGIN
DECLARE @PositionShemaBinding INT
DECLARE @Command NVARCHAR(MAX)
SELECT @Command = OBJECT_DEFINITION(OBJECT_ID(@ViewName));
SET @PositionShemaBinding = CHARINDEX('WITH SCHEMABINDING', @Command)
IF NOT @PositionShemaBinding = 0 BEGIN
-- WITH SCHEMA BINDING IS PRESENT... Let's remove it !
SET @Command = STUFF(@Command, CHARINDEX('WITH SCHEMABINDING', @Command), LEN('WITH SCHEMABINDING'), '');
SET @Command = REPLACE(@Command, 'CREATE VIEW', 'ALTER VIEW');
EXECUTE sp_executesql @Command
END
END
And to put the SCHEMABINDING :
CREATE PROCEDURE ViewAddSchemaBinding
@ViewName VARCHAR(MAX)
AS
BEGIN
DECLARE @PositionShemaBinding INT
DECLARE @Command NVARCHAR(MAX)
DECLARE @ObjectName VARCHAR(MAX)
SELECT @Command = OBJECT_DEFINITION(OBJECT_ID(@ViewName)),
@ObjectName = OBJECT_NAME(OBJECT_ID(@ViewName));
SET @PositionShemaBinding = PATINDEX('%WITH SCHEMABINDING%', @Command)
IF @PositionShemaBinding = 0 BEGIN
-- WITH SCHEMA BINDING IS NOT PRESENT... Let's add it !
SET @Command = REPLACE(@Command, 'CREATE VIEW', 'ALTER VIEW');
-- IF OBJECT NAME IS INTO BRAKETS, We need to handle it
IF NOT CHARINDEX('[' + @ObjectName + ']', @Command) = 0 BEGIN
SET @ObjectName = '[' + @ObjectName + ']'
END
SET @Command = STUFF(@Command, CHARINDEX(@ObjectName, @Command), LEN(@ObjectName), @ObjectName + ' WITH SCHEMABINDING ');
EXECUTE sp_executesql @Command
END
END
It is provided "as is"...