[SQL] DROP CREATE « pattern » (MSSQL)

Simple reminder for a working drop-create pattern in SQL (Successfully used with MSSQL).

Log modification in table _chgLog first.

INSERT INTO _chgLog ([Date], [Version], [txt], [Type])
    VALUES (GETDATE(), '0.0.1', 'Update example', 0)
GO

If object exists, we drop it before doing anything (But do not drop table unless you don’t care about data).

IF OBJECTPROPERTY(object_id('example'), N'IsProcedure') = 1
    DROP PROCEDURE [dbo].[example]
GO

Other interesting parameters for function objectproperty are the following (more to be found here) :

  • IsInlineFunction
  • IsProcedure
  • IsScalarFunction
  • IsTable
  • IsTableFunction
  • IsTrigger
  • IsView

Then, we create the object.

-- =============================================
-- Author: vvision
-- Create date: 22/03/2016
-- Description: <Description>
-- =============================================

CREATE PROCEDURE [dbo].[example]
  @id INT,
AS
  SELECT *
  FROM [dbo].[example]
  WHERE id = @id
GO

Finally, we give permissions to users if needed.

GRANT EXECUTE ON [dbo].[example] TO [user] AS [dbo]
GO

 

On another subject, to alter a table, we can use:

IF COL_LENGTH('table','newField') IS NULL
BEGIN
  ALTER TABLE [dbo].[table] ADD newField VARCHAR(128) NULL
END