Wednesday, February 27, 2013

If Exists Logic

If exists logic for a Database

IF EXISTS(select * from sys.databases where name='yourDBname')

If exists logic for a table

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DimPACodes]') AND type in (N'U'))

If exists logic for a synonms

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N's_DimPACodes') AND type in (N'SN'))

If exists logic for a View

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'vw_DimProgram') AND type in (N'V'))

If exists logic for a column

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Dimprogram' and COLUMN_NAME = 'IAPKey')

If exists logic for a Schema


IF NOT EXISTS(SELECT * FROM sys.schemas where name = N'Test')
EXEC ('CREATE SCHEMA [telligent] Authorization [dbo]')
GO

(OR)

IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Test')
EXEC ('CREATE SCHEMA [Test] Authorization [dbo]')
GO



Interpreting type codes in sys.objects in SQL Server

AF = Aggregate function (CLR)
C  = CHECK constraint
D  = DEFAULT (constraint or stand-alone)
F  = FOREIGN KEY constraint
FN = SQL scalar function
FS = Assembly (CLR) scalar-function
FT = Assembly (CLR) table-valued function
IF = SQL inline table-valued function
IT = Internal table
P  = SQL Stored Procedure
PC = Assembly (CLR) stored-procedure
PG = Plan guide
PK = PRIMARY KEY constraint
R  = Rule (old-style, stand-alone)
RF = Replication-filter-procedure
S  = System base table
SN = Synonym
SQ = Service queue
TA = Assembly (CLR) DML trigger
TF = SQL table-valued-function
TR = SQL DML trigger
TT = Table type
U  = Table (user-defined)
UQ = UNIQUE constraint
V  = View
X  = Extended stored procedure

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.