Showing posts with label if not exists. Show all posts
Showing posts with label if not exists. Show all posts

CREATE new schema and ALTER table schema

To create a new Database Schema:
CREATE SCHEMA NewSchema
GO

To create a new Database Schema only if it does not exist:
IF NOT EXISTS (SELECT * FROM sys.schemas
WHERE name ='NewSchema')

EXEC dbo.sp_executesql @statement=N'
CREATE SCHEMA NewSchema'
;
GO


To change a table's Schema:
ALTER SCHEMA NewSchema TRANSFER OldSchema.TableName;
--default schema is dbo then:
ALTER SCHEMA NewSchema TRANSFER dbo.TableName;

Add DB Role IF NOT EXISTS

Check if the Database Role exists before creating it:

DECLARE @Role varchar(20) = 'UserRole'
IF NOT EXISTS (SELECT name FROM sysusers
WHERE issqlrole=1 AND name = @Role)

EXEC sp_addrole @Role; --EXEC sp_addrole @Role, 'dbo'

Create Stored Procedure IF NOT EXISTS (SQL Server)

This is especially useful if you're writing update scripts like I am.

IF NOT EXISTS(Select * from sysobjects where name = 'usp_UserSproc')
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE usp_UserSproc
(
@ID int = NULL --nullable input
)

AS
BEGIN
SET NOCOUNT ON;
IF @ID IS NOT NULL
SELECT * FROM My_Table WHERE ID=@ID;
ELSE
SELECT * FROM My_Table WHERE ID=1;
END';
END