declare @tableName varchar(200)
set @tableName = 'ssis_tasks'
select * from sys.foreign_keys k
inner join sys.tables t on t.[object_id] = k.referenced_object_id
where t.[name] = @tableName
SELECT * FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where CONSTRAINT_NAME in
(
select k.name from sys.foreign_keys k
inner join sys.tables t on t.[object_id] = k.referenced_object_id
where t.[name] = @tableName
)
Thursday, February 18, 2010
Thursday, February 11, 2010
Run SP automatically when SQL Server starts
EXECUTE sp_procoption
@procname = 'usp_StartTrace',
@optionname = 'startup',
@optionvalue = 'on'
@procname = 'usp_StartTrace',
@optionname = 'startup',
@optionvalue = 'on'
Identify Primary Keys and PK column name
SELECT KU.*
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND
TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
ORDER BY KU.TABLE_NAME, KU.ORDINAL_POSITION
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND
TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
ORDER BY KU.TABLE_NAME, KU.ORDINAL_POSITION
Tuesday, February 09, 2010
Change Tracking with SQL 2008
USE [Test]
GO
DROP TABLE [ChangeTrack]
GO
CREATE TABLE [dbo].[ChangeTrack](
[LineID] [int] IDENTITY(1000,1) NOT NULL,
[Fname] [nvarchar](100) NULL,
[Lname] [nvarchar](100) NULL,
[InsertDate] [datetime] NULL,
CONSTRAINT [PK_ChangeTrack] PRIMARY KEY CLUSTERED
(
[LineID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ChangeTrack] ADD CONSTRAINT [DF_ChangeTrack_InsertDate] DEFAULT (getdate()) FOR [InsertDate]
GO
ALTER TABLE [dbo].[ChangeTrack] ENABLE CHANGE_TRACKING WITH(TRACK_COLUMNS_UPDATED = ON)
GO
declare @synchronization_version bigint , @last_synchronization_version bigint
set @last_synchronization_version = CHANGE_TRACKING_CURRENT_VERSION()
waitfor delay '00:00:05'
--load table
insert into [ChangeTrack] (Fname, Lname ) values ('Pat','Rick'), ('Pat','Rick'),('Pat','Rick'),('Pat','Rick'),('Pat','Rick'),('Pat','Rick'),('Pat','Rick'),('Pat','Rick'),('Pat','Rick'),('Pat','Rick')
waitfor delay '00:00:05'
--Obtain initial data set.
--SELECT * FROM [ChangeTrack]
--Using the Change Tracking Functions to Obtain Changes
--declare @last_synchronization_version bigint
--set @last_synchronization_version = 1302
set transaction isolation level snapshot
begin transaction
SELECT
Getdate(), CT.[LineID], CT.SYS_CHANGE_OPERATION,
CT.SYS_CHANGE_COLUMNS, CT.SYS_CHANGE_CONTEXT
FROM
CHANGETABLE(CHANGES [ChangeTrack], @last_synchronization_version) AS CT
set @last_synchronization_version = CHANGE_TRACKING_CURRENT_VERSION()
commit
/*
SELECT
CT.[LineID], P.*,
CT.SYS_CHANGE_OPERATION, CT.SYS_CHANGE_COLUMNS,
CT.SYS_CHANGE_CONTEXT
FROM
[ChangeTrack] AS P
RIGHT OUTER JOIN
CHANGETABLE(CHANGES [ChangeTrack], @last_synchronization_version) AS CT
ON
P.[LineID] = CT.[LineID]
*/
--select CHANGE_TRACKING_CURRENT_VERSION();
waitfor delay '00:00:05'
--some updates
update [ChangeTrack] set Fname = Fname + '_CHANGED' where LineID % 10 = 4
waitfor delay '00:00:05'
--Using the Change Tracking Functions to Obtain Changes
--declare @last_synchronization_version bigint
--set @last_synchronization_version = 1312
set transaction isolation level snapshot
begin transaction
SELECT
Getdate(), CT.[LineID], CT.SYS_CHANGE_OPERATION,
CT.SYS_CHANGE_COLUMNS, CT.SYS_CHANGE_CONTEXT
FROM
CHANGETABLE(CHANGES [ChangeTrack], @last_synchronization_version) AS CT
set @last_synchronization_version = CHANGE_TRACKING_CURRENT_VERSION()
commit
/*
SELECT
CT.[LineID], P.*,
CT.SYS_CHANGE_OPERATION, CT.SYS_CHANGE_COLUMNS,
CT.SYS_CHANGE_CONTEXT
FROM
[ChangeTrack] AS P
RIGHT OUTER JOIN
CHANGETABLE(CHANGES [ChangeTrack], @last_synchronization_version) AS CT
ON
P.[LineID] = CT.[LineID]
*/
--select CHANGE_TRACKING_CURRENT_VERSION();
waitfor delay '00:00:05'
--some insert/update/delete
insert into [ChangeTrack] (Fname, Lname ) values ('Pat111','Rick111'),('Pat111','Rick111'),('Pat111','Rick111'),('Pat111','Rick111'),('Pat111','Rick111')
update [ChangeTrack] set Fname = '123' where LineID % 10 = 5
delete from [ChangeTrack] where LineID % 10 = 6
waitfor delay '00:00:05'
--select * from [ChangeTrack]
--Using the Change Tracking Functions to Obtain Changes
--declare @last_synchronization_version bigint
--set @last_synchronization_version = 1313
set transaction isolation level snapshot
begin transaction
SELECT
Getdate(), CT.[LineID], CT.SYS_CHANGE_OPERATION,
CT.SYS_CHANGE_COLUMNS, CT.SYS_CHANGE_CONTEXT
FROM
CHANGETABLE(CHANGES [ChangeTrack], @last_synchronization_version) AS CT
set @last_synchronization_version = CHANGE_TRACKING_CURRENT_VERSION()
commit
/*
SELECT
CT.[LineID], P.*,
CT.SYS_CHANGE_OPERATION, CT.SYS_CHANGE_COLUMNS,
CT.SYS_CHANGE_CONTEXT
FROM
[ChangeTrack] AS P
RIGHT OUTER JOIN
CHANGETABLE(CHANGES [ChangeTrack], @last_synchronization_version) AS CT
ON
P.[LineID] = CT.[LineID]
*/
--select CHANGE_TRACKING_CURRENT_VERSION()
GO
DROP TABLE [ChangeTrack]
GO
CREATE TABLE [dbo].[ChangeTrack](
[LineID] [int] IDENTITY(1000,1) NOT NULL,
[Fname] [nvarchar](100) NULL,
[Lname] [nvarchar](100) NULL,
[InsertDate] [datetime] NULL,
CONSTRAINT [PK_ChangeTrack] PRIMARY KEY CLUSTERED
(
[LineID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ChangeTrack] ADD CONSTRAINT [DF_ChangeTrack_InsertDate] DEFAULT (getdate()) FOR [InsertDate]
GO
ALTER TABLE [dbo].[ChangeTrack] ENABLE CHANGE_TRACKING WITH(TRACK_COLUMNS_UPDATED = ON)
GO
declare @synchronization_version bigint , @last_synchronization_version bigint
set @last_synchronization_version = CHANGE_TRACKING_CURRENT_VERSION()
waitfor delay '00:00:05'
--load table
insert into [ChangeTrack] (Fname, Lname ) values ('Pat','Rick'), ('Pat','Rick'),('Pat','Rick'),('Pat','Rick'),('Pat','Rick'),('Pat','Rick'),('Pat','Rick'),('Pat','Rick'),('Pat','Rick'),('Pat','Rick')
waitfor delay '00:00:05'
--Obtain initial data set.
--SELECT * FROM [ChangeTrack]
--Using the Change Tracking Functions to Obtain Changes
--declare @last_synchronization_version bigint
--set @last_synchronization_version = 1302
set transaction isolation level snapshot
begin transaction
SELECT
Getdate(), CT.[LineID], CT.SYS_CHANGE_OPERATION,
CT.SYS_CHANGE_COLUMNS, CT.SYS_CHANGE_CONTEXT
FROM
CHANGETABLE(CHANGES [ChangeTrack], @last_synchronization_version) AS CT
set @last_synchronization_version = CHANGE_TRACKING_CURRENT_VERSION()
commit
/*
SELECT
CT.[LineID], P.*,
CT.SYS_CHANGE_OPERATION, CT.SYS_CHANGE_COLUMNS,
CT.SYS_CHANGE_CONTEXT
FROM
[ChangeTrack] AS P
RIGHT OUTER JOIN
CHANGETABLE(CHANGES [ChangeTrack], @last_synchronization_version) AS CT
ON
P.[LineID] = CT.[LineID]
*/
--select CHANGE_TRACKING_CURRENT_VERSION();
waitfor delay '00:00:05'
--some updates
update [ChangeTrack] set Fname = Fname + '_CHANGED' where LineID % 10 = 4
waitfor delay '00:00:05'
--Using the Change Tracking Functions to Obtain Changes
--declare @last_synchronization_version bigint
--set @last_synchronization_version = 1312
set transaction isolation level snapshot
begin transaction
SELECT
Getdate(), CT.[LineID], CT.SYS_CHANGE_OPERATION,
CT.SYS_CHANGE_COLUMNS, CT.SYS_CHANGE_CONTEXT
FROM
CHANGETABLE(CHANGES [ChangeTrack], @last_synchronization_version) AS CT
set @last_synchronization_version = CHANGE_TRACKING_CURRENT_VERSION()
commit
/*
SELECT
CT.[LineID], P.*,
CT.SYS_CHANGE_OPERATION, CT.SYS_CHANGE_COLUMNS,
CT.SYS_CHANGE_CONTEXT
FROM
[ChangeTrack] AS P
RIGHT OUTER JOIN
CHANGETABLE(CHANGES [ChangeTrack], @last_synchronization_version) AS CT
ON
P.[LineID] = CT.[LineID]
*/
--select CHANGE_TRACKING_CURRENT_VERSION();
waitfor delay '00:00:05'
--some insert/update/delete
insert into [ChangeTrack] (Fname, Lname ) values ('Pat111','Rick111'),('Pat111','Rick111'),('Pat111','Rick111'),('Pat111','Rick111'),('Pat111','Rick111')
update [ChangeTrack] set Fname = '123' where LineID % 10 = 5
delete from [ChangeTrack] where LineID % 10 = 6
waitfor delay '00:00:05'
--select * from [ChangeTrack]
--Using the Change Tracking Functions to Obtain Changes
--declare @last_synchronization_version bigint
--set @last_synchronization_version = 1313
set transaction isolation level snapshot
begin transaction
SELECT
Getdate(), CT.[LineID], CT.SYS_CHANGE_OPERATION,
CT.SYS_CHANGE_COLUMNS, CT.SYS_CHANGE_CONTEXT
FROM
CHANGETABLE(CHANGES [ChangeTrack], @last_synchronization_version) AS CT
set @last_synchronization_version = CHANGE_TRACKING_CURRENT_VERSION()
commit
/*
SELECT
CT.[LineID], P.*,
CT.SYS_CHANGE_OPERATION, CT.SYS_CHANGE_COLUMNS,
CT.SYS_CHANGE_CONTEXT
FROM
[ChangeTrack] AS P
RIGHT OUTER JOIN
CHANGETABLE(CHANGES [ChangeTrack], @last_synchronization_version) AS CT
ON
P.[LineID] = CT.[LineID]
*/
--select CHANGE_TRACKING_CURRENT_VERSION()
Labels:
Change Tracking,
Rowversion,
SQL2008,
Timestamp
PIVOT , UNPIVOT
--Create the table and insert values as portrayed in the previous example.
CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,
Emp3 int, Emp4 int, Emp5 int);
GO
INSERT INTO pvt VALUES (1,4,3,5,4,4);
INSERT INTO pvt VALUES (2,4,1,5,5,5);
INSERT INTO pvt VALUES (3,4,3,5,4,4);
INSERT INTO pvt VALUES (4,4,2,5,5,4);
INSERT INTO pvt VALUES (5,5,1,5,5,5);
GO
select * from pvt
--Unpivot the table.
SELECT VendorID, Employee, Orders
into #tmp
FROM
(SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
FROM pvt) p
UNPIVOT
(Orders FOR Employee IN
(Emp1, Emp2, Emp3, Emp4, Emp5)
)AS unpvt;
GO
select * from #tmp
select * from pvt
-- pivot table
select *
from #tmp
pivot
(
sum(orders)
for employee in (Emp1, Emp2, Emp3, Emp4, Emp5)
) as p
---------------------------
--dynamic creation
declare @str nvarchar(1000)
set @str = ''
select @str = @str + employee+ ',' from #tmp group by employee
set @str = left(@str, LEN(@str)-1)
select @str
declare @sql nvarchar(1000)
set @sql = '
select *
from #tmp
pivot
(
sum(orders)
for employee in ('+@str+')
) as p'
print @sql
exec sp_executesql @sql
---------------------------
CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,
Emp3 int, Emp4 int, Emp5 int);
GO
INSERT INTO pvt VALUES (1,4,3,5,4,4);
INSERT INTO pvt VALUES (2,4,1,5,5,5);
INSERT INTO pvt VALUES (3,4,3,5,4,4);
INSERT INTO pvt VALUES (4,4,2,5,5,4);
INSERT INTO pvt VALUES (5,5,1,5,5,5);
GO
select * from pvt
--Unpivot the table.
SELECT VendorID, Employee, Orders
into #tmp
FROM
(SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
FROM pvt) p
UNPIVOT
(Orders FOR Employee IN
(Emp1, Emp2, Emp3, Emp4, Emp5)
)AS unpvt;
GO
select * from #tmp
select * from pvt
-- pivot table
select *
from #tmp
pivot
(
sum(orders)
for employee in (Emp1, Emp2, Emp3, Emp4, Emp5)
) as p
---------------------------
--dynamic creation
declare @str nvarchar(1000)
set @str = ''
select @str = @str + employee+ ',' from #tmp group by employee
set @str = left(@str, LEN(@str)-1)
select @str
declare @sql nvarchar(1000)
set @sql = '
select *
from #tmp
pivot
(
sum(orders)
for employee in ('+@str+')
) as p'
print @sql
exec sp_executesql @sql
---------------------------
Monday, February 01, 2010
Data Type GEOMETRY usage to draw my face
SELECT geometry::Point(x, y, 0).STBuffer(0.4) As sig
FROM ( VALUES
(02,16),(02,17),(02,19),(02,20),(02,25),(02,26),(02,27),(02,28),(03,29),(03,30),(02,31),(02,32),(02,33),
(03,15),(03,22),(03,23),(03,24),(03,26),(03,27),(03,28),(03,29),(03,30),(03,31),(03,32),(03,33),(03,34),(03,35),(03,36),
(04,31),(04,32),(04,33),(04,34),(04,35),(04,36),(04,37),
(05,35),(05,36),(05,37),(05,38),(05,39),(05,40),
(06,23),(06,26),(06,37),(06,38),(06,39),(06,40),
(07,23),(07,24),(07,26),(07,38),(07,39),(07,40),(07,41),
(08,16),(08,22),(08,23),(08,24),(08,26),(08,27),(08,40),(08,41),(08,42),
(09,12),(09,13),(09,23),(09,24),(09,26),(09,27),(09,41),
(10,12),(10,13),(10,23),(10,24),(10,25),(10,26),(10,27),(10,43),
(11,13),(11,23),(11,24),(11,25),(11,39),(11,41),
(12,02),(12,13),(12,22),(12,23),(12,25),(12,38),(12,39),(12,40),(12,41),
(13,01),(13,02),(13,10),(13,13),(13,16),(13,17),(13,39),(13,40),(13,41),(13,42),
(14,01),(14,02),(14,07),(14,12),(14,39),(14,40),(14,41),(14,42),
(15,01),(15,07),(15,39),(15,40),(15,41),(15,42),(15,43),
(16,01),(16,15),(16,40),(16,41),(16,42),(16,43),
(17,01),(17,10),(17,16),(17,40),(17,41),(17,42),(17,43),
(18,01),(18,10),(18,13),(18,16),(18,40),(18,41),(18,42),(18,43),
(19,01),(19,10),(19,13),(19,16),(19,23),(19,24),(19,25),(19,39),(19,40),(19,41),(19,42),
(20,01),(20,06),(20,10),(20,11),(20,12),(20,22),(20,23),(20,24),(20,25),(20,26),(20,40),(20,41),(20,42),
(21,02),(21,03),(21,05),(21,06),(21,11),(21,12),(21,22),(21,23),(21,24),(21,25),(21,26),(21,40),(21,41),(21,42),
(22,02),(22,03),(22,12),(22,16),(22,17),(22,22),(22,23),(22,26),(22,27),(22,40),(22,41),
(23,03),(23,04),(23,05),(23,06),(23,12),(23,23),(23,24),(23,27),(23,40),(23,41),
(24,04),(24,05),(24,23),(24,24),
(25,04),(25,05),(25,06),(25,23),(25,24),(25,27),
(26,05),(26,06),(26,07),(26,23),(26,27),
(27,06),(27,07),(27,37),(27,38),(27,39),
(28,07),(28,22),(28,23),(28,24),(28,28),(28,29),(28,30),(28,31),(28,32),(28,35),(28,36),(28,37),(28,38),(28,39),
(29,08),(29,09),(29,24),(29,26),(29,27),(29,28),(29,29),(29,30),(29,31),(29,32),(29,33),(29,34),(29,35),(29,36),(29,37),(29,38),
(30,12),(30,28),(30,29),(30,30),(30,31),(30,32),(30,33),(30,34),(30,35),(30,36),
(31,12),(31,17),(31,18),(31,19),(31,20),(31,21),(31,22),(31,23),(31,24),(31,25),(31,26),(31,27),(31,28),(31,29),(31,30),(31,31),(31,32),(31,33),
(32,21),(32,22),(32,23),(32,24),(32,25),(32,26),(32,27),(32,28)
) AS Coordinates(x, y);
FROM ( VALUES
(02,16),(02,17),(02,19),(02,20),(02,25),(02,26),(02,27),(02,28),(03,29),(03,30),(02,31),(02,32),(02,33),
(03,15),(03,22),(03,23),(03,24),(03,26),(03,27),(03,28),(03,29),(03,30),(03,31),(03,32),(03,33),(03,34),(03,35),(03,36),
(04,31),(04,32),(04,33),(04,34),(04,35),(04,36),(04,37),
(05,35),(05,36),(05,37),(05,38),(05,39),(05,40),
(06,23),(06,26),(06,37),(06,38),(06,39),(06,40),
(07,23),(07,24),(07,26),(07,38),(07,39),(07,40),(07,41),
(08,16),(08,22),(08,23),(08,24),(08,26),(08,27),(08,40),(08,41),(08,42),
(09,12),(09,13),(09,23),(09,24),(09,26),(09,27),(09,41),
(10,12),(10,13),(10,23),(10,24),(10,25),(10,26),(10,27),(10,43),
(11,13),(11,23),(11,24),(11,25),(11,39),(11,41),
(12,02),(12,13),(12,22),(12,23),(12,25),(12,38),(12,39),(12,40),(12,41),
(13,01),(13,02),(13,10),(13,13),(13,16),(13,17),(13,39),(13,40),(13,41),(13,42),
(14,01),(14,02),(14,07),(14,12),(14,39),(14,40),(14,41),(14,42),
(15,01),(15,07),(15,39),(15,40),(15,41),(15,42),(15,43),
(16,01),(16,15),(16,40),(16,41),(16,42),(16,43),
(17,01),(17,10),(17,16),(17,40),(17,41),(17,42),(17,43),
(18,01),(18,10),(18,13),(18,16),(18,40),(18,41),(18,42),(18,43),
(19,01),(19,10),(19,13),(19,16),(19,23),(19,24),(19,25),(19,39),(19,40),(19,41),(19,42),
(20,01),(20,06),(20,10),(20,11),(20,12),(20,22),(20,23),(20,24),(20,25),(20,26),(20,40),(20,41),(20,42),
(21,02),(21,03),(21,05),(21,06),(21,11),(21,12),(21,22),(21,23),(21,24),(21,25),(21,26),(21,40),(21,41),(21,42),
(22,02),(22,03),(22,12),(22,16),(22,17),(22,22),(22,23),(22,26),(22,27),(22,40),(22,41),
(23,03),(23,04),(23,05),(23,06),(23,12),(23,23),(23,24),(23,27),(23,40),(23,41),
(24,04),(24,05),(24,23),(24,24),
(25,04),(25,05),(25,06),(25,23),(25,24),(25,27),
(26,05),(26,06),(26,07),(26,23),(26,27),
(27,06),(27,07),(27,37),(27,38),(27,39),
(28,07),(28,22),(28,23),(28,24),(28,28),(28,29),(28,30),(28,31),(28,32),(28,35),(28,36),(28,37),(28,38),(28,39),
(29,08),(29,09),(29,24),(29,26),(29,27),(29,28),(29,29),(29,30),(29,31),(29,32),(29,33),(29,34),(29,35),(29,36),(29,37),(29,38),
(30,12),(30,28),(30,29),(30,30),(30,31),(30,32),(30,33),(30,34),(30,35),(30,36),
(31,12),(31,17),(31,18),(31,19),(31,20),(31,21),(31,22),(31,23),(31,24),(31,25),(31,26),(31,27),(31,28),(31,29),(31,30),(31,31),(31,32),(31,33),
(32,21),(32,22),(32,23),(32,24),(32,25),(32,26),(32,27),(32,28)
) AS Coordinates(x, y);
Thursday, January 21, 2010
Merge tables Sample
select * from [target_stage]
Merge into [target] as t
using target_stage s on t.lineid = s.lineid
when matched then update
set t.fname = s.fname ,
t.lname = s.lname,
t.[ModifiedTimeStamp] = s.[ModifiedTimeStamp]
when not matched then insert ([LineID],[Fname],[Lname],[InsertDate],[ModifiedTimeStamp])
values (s.[LineID],s.[Fname],s.[Lname],s.[InsertDate],s.[ModifiedTimeStamp])
when not matched by source then delete
output INSERTED.Lineid;
select * from [target]
Merge into [target] as t
using target_stage s on t.lineid = s.lineid
when matched then update
set t.fname = s.fname ,
t.lname = s.lname,
t.[ModifiedTimeStamp] = s.[ModifiedTimeStamp]
when not matched then insert ([LineID],[Fname],[Lname],[InsertDate],[ModifiedTimeStamp])
values (s.[LineID],s.[Fname],s.[Lname],s.[InsertDate],s.[ModifiedTimeStamp])
when not matched by source then delete
output INSERTED.Lineid;
select * from [target]
Wednesday, January 20, 2010
Search all columns in all the tables in a database for a specific value
Search all columns in all the tables in a database for a specific value:
http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/the-ten-most-asked-sql-server-questions--1#2
http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/the-ten-most-asked-sql-server-questions--1#2
Monday, January 11, 2010
SQL Naming & Coding Convention Standards
Valid Characters
Alphanumeric characters only ([a-zA-Z0-9]) – In every case only alphanumeric characters (and some situations underscore) are allowed
General Rules
The following rules should apply to all database objects.
• Clear and unambiguous naming.
o The name should provide as much information as possible about an object and provide an obvious connection to references in project documentation. Choice of names should typically consider a name space much larger than a project—preferably the enterprise. A name uniquely identifies a database object; its definition should be consistent wherever the object is used. What might seem clear in a narrow context may lose meaning outside of that context. Saving keystrokes should never be used as a criterion in selecting a name.
• Abbreviations should be avoided.
o Only when length restrictions apply should they be permitted. When used, abbreviations should follow the abbreviation rules.
o Example :
--Correct
DECLARE @Counter int
--Avoid
DECLARE @C int
• Alphanumeric characters only ([a-zA-Z0-9]) – Do not use special characters; restrict names to alphanumeric characters, no space is allowed in object name:
o Example :
--Avoid
CREATE TABLE dbo.[User Information]
• System naming should be avoided. Do not use any prefix or object names that somehow links to system object. No DB object can be created under “SYS” schema and there are limitations on prefixes on Stored procedures too, Please check Stored Procedure section for more details.
• Use Upper case for all T-SQL constructs (except types).
o Example : SELECT MAX(MyField) FROM MyTable
• Use Lower case for all T-SQL types and usernames:
o Example : DECLARE @MyVariable int
Database Object Naming Rules
Summary:
Object Prefix Suffix Alpha Numeric Characters Notes
Tables x Use singular form: Example User, not Users
Linking Tables _Link x Formed from the Tables they are linking, Example: A Table joining User and Group would be UserGroupLink
Table Columns x
Primary Key PK_ x
Clustered Index IXC_ x
Unique Clustered Index IXCU_ x
Unique Index IXU_ x
Index IX_ x
XML Index XML_IX_ x
XML Columns x Use .net casing, no underscores
Constraints CK_ x
Default Value DF_ x
Foreign Keys FK_ x
Views VW_ x
Functions FN_ x
Stored Procedures PR_ x
Triggers (after) TRGA_ x
Triggers (instead) TRGI_ x
CTE (Common Table Expressions) CTE_ x
Schemas
• Use lowercase for schema names.
• Always alias database objects using the schema name, even if this is the default [dbo] schema
• This applies to both CREATE statements and when referencing objects in FROM, INSERT or UPDATE statements etc.
Table Names
• Prefixes are used to identify the table with relation to application modules as much as possible. Some of the most common prefixes are as :
• ANALYTICS_
• AUDIT_
• BILLING_
• CAREER_
• CERT_
• CMP_
• COMMENT_
• COMPASSES_
• CONNECT_
• CORP_
• DESIGNATION_
• DEVPLAN_
• EMAIL_
• EVALUATION_
• LCMS_
• LICENSE_
• LO_
• OU_
• PO_
• PROXY_
• QTI_
• REPORT_
• RESUME_
• REVIEW_
• SECURITY_
• SMP_
• SOAP_
• TALENT_
• TASK_
• USER_
• WAREHOUSE_
• Alphanumeric characters only
• Always assign schema name to UDO’s (User Define Object) when defining or referencing
• Example :
--Correct
CREATE TABLE dbo.MyTable (...)
--Avoid
CREATE TABLE MyTable (...)
• Use the Singular Form Example : User, not Users
• Example :
--Correct
CREATE TABLE dbo.Address
--Avoid
CREATE TABLE dbo.Addresses
--Correct
SELECT * FROM dbo.MyTable (...)
--Avoid
SELECT * FROM MyTable (...)
Linking Table Names
• Linking Tables should be the name of the two tables it is joining, suffixed with _Link. Eg a joining table on User and Group would be User_Group_Link
Column Names
• Alpha-numeric
• No Prefix
• Format:
use the following components in the order below;
o Table Name: Primary keys only; Tables names are used to prefix all columns in dotted format, so this is not necessarily. The exception is the primary key since this is used in foreign keys.
o Qualifier: Optional; Description, to clarify the meaning of the field. For example, if a product has two images, this would clarify the field, eg. FrontImage and RearImage
o Name: Required; This is a database independent “datatype” descriptor which is used to classify the type of data. Below is a common list of standard classifiers. The exception to this is a Boolean. This should be Prefixed with “Is” as this more positively represents the meaning o the value. Flag suffix is considered optional “Flag” or Example. IsEnabled or IsEnabledFlag
Classifier Description Suggested SQL Data Type
Address Street or mailing address data nvarchar
Age Chronological age in years int
Average Average; consider a computed column numeric
Amount Currency amount money
Code Non Database Identifier
Count
Data A field containing extensible data xml
Date Calendar date smalldatetime
Datetime Date including time datetime
Day Day of month (1 - 31) tinyint
Description Brief narrative description nvarchar(MAX)
Duration Length of time, eg minutes int
ID Unique identifier for something int
Image A graphic image, such as a bitmap varbinary(MAX)
Flag Not Required: Flag indicates a boolean indicator, where the Qualifier verb does not make it clear it is a verb. Examples of a Qualifier are: Is, Has, Uses. Eg IsEnabled bit
Month Month of year
Name Formal name nvarchar
Number
Percent Number expressed as a percent
Quantity A number of things any numerical
Rate Number expressed as a rate any numerical
Ratio A proportion, or expression of relationship in quantity, size, amount, etc. between two things any numerical
Sequence A numeric order field int
Text Freeform textual information nvarchar(MAX)
Time Time of day smalldatetime
Title Formal name of something nvarchar
Version Timestamp timestamp
Weight Weight measurement any numerical
XML A field containing xml data xml
Year Calendar year or julian year number
Stored Procedure Names
• Naming Format: use the following components in the order below;
o Object: Required; usually the table or combinations of tables it is affecting, followed by underscore.
o Action: Required; eg Save, Load, Get, Set, SetSingle, Search, Delete
o Qualifier: Optional; additional descriptive words which help to clarify the specific meaning of the stored procedure
o Return Type: Optional; Indicates the type of data return
• Example Stored Procedure Names:
o pr_cmp_adjustment_save
o pr_cmp_adjustment_delete
o pr_cmp_adjustment_get
o pr_cmp_adjustment_search
• Do not:
o Use special characters.
o Use stored procedure group numbers (e.g. myProc;1).
o Prefix names with “dt_” or “sp_” or “xp_” as those are reserved for procedures shipped by SQL Server.
• Always create scope when defining Procedures and multi statement functions.
o Example :
--Correct
CREATE PROCEDURE dbo.uspMyProcedure
AS
BEGIN
(...)
END
--Avoid
CREATE PROCEDURE dbo.uspMyProcedure
AS
(...)
• When joining table always identify all columns with aliases and always alias the AS keyword.
o Example :
--Correct
SELECT U.Surname,
A.Street
FROM dbo.[User] AS U
JOIN dbo.Address AS A ON U.AddressID = A.AddressID
--Avoid
SELECT U.Surname,
Street –-Missing alias
FROM Users U –-Missing AS
JOIN dbo.Address ON U.AddressID = dbo.Address.AddressID
• When defining procedures and functions, include a commented Test Harness. Declare used variables for usage in testing:
o Example :
--Correct
CREATE FUNCTION dbo.tvfMyFunction
(
@MyParameter int
)
AS
/* TEST HARNESS
DECLARE @MyParameter int
SET @MyParameter = 1
SELECT * FROM dbo.tvfMyFunction(@MyParameter)
*/
(...)
--Correct
CREATE PROCEDURE dbo.uspMyProcedure
(
@MyParameter int
)
AS
/* TEST HARNESS
DECLARE @MyParameter int
SET @MyParameter = 1
BEGIN TRAN
SELECT * FROM dbo.MyTable –-MyTable before operation
EXEC dbo.uspMyProcedure(@MyParameter)
SELECT * FROM dbo.MyTable –-MyTable after operation
ROLLBACK TRAN
*/
(...)
--Avoid
/* TEST HARNESS
SELECT * FROM dbo.tvfMyFunction(1) –-argument not declared
*/
• Always individually name fields in INSERT and UPDATE statements. Never use the * operator in such statements.
o Example :
--Correct
INSERT INTO dbo.[User] (FirstName, LastName)
VALUES (@FirstName, @LastName)
--Avoid
INSERT INTO dbo.[User]
VALUES (@FirstName, @LastName)
• Set the NOCOUNT state as the first statement in all Procedures where you don’t specifically need the count returned.
o Example :
--Correct
CREATE PROCEDURE dbo.uspMyProcedure (...)
AS
BEGIN
SET NOCOUNT ON
(...)
• Set ISOLATION LEVEL READ UNCOMMITTED for retrieving data procs. This option has the same effect as setting NOLOCK on all tables in all SELECT statements in a transaction. This is the least restrictive of the four isolation levels.
o Example :
--Correct
Select FirstName, LastName FROM dbo.[User] With (Nolock)
--Avoid
Select * FROM dbo.[User]
User Defined Functions (UDF) Names
• Naming Format: use the following components in the order below;
o Prefix: Required; “FN_”
o Object: Required; usually the table or combinations of tables it is affecting, followed by underscore.
o Action: Required; eg Get, Set, SetSingle, Search, Delete
o Qualifier: Optional; additional descriptive words which help to clarify the specific meaning of the stored procedure
o Return Type: Optional; Indicates the type of data return
• Example Function Names:
o fn_get_credential_name
Parameters and Parameters Type - Stored Procedure/UDFs
Example : Decalre @PageID int
Data types should be lowercase, like “int”, “nvarchar(100)”
Variables - Stored Procedure/UDFs
Example : Decalre @PageID int
Data types should be lowercase, like “int”, “nvarchar(100)”
Recursive (CTE or while loop)
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix with “CTE_”
o Object: Required; usually the table being iterated over.
o Substitute for a view when the general use of a view is not required; that is, you do not have to store the definition in metadata
• Example :
WITH CTE_Sales (SalesPersonID, NumberOfOrders, MaxDate)
AS
(
SELECT SalesPersonID, COUNT(*), MAX(OrderDate)
FROM Sales.SalesOrderHeader
GROUP BY SalesPersonID
)
SELECT E.EmployeeID, OS.NumberOfOrders, OS.MaxDate,
E.ManagerID, OM.NumberOfOrders, OM.MaxDate
FROM HumanResources.Employee AS E
JOIN CTE_Sales AS OS ON E.EmployeeID = OS.SalesPersonID
LEFT OUTER JOIN CTE_Sales AS OM ON E.ManagerID = OM.SalesPersonID
ORDER BY E.EmployeeID;
GO
• Note: Avoid the use of cursors where possible. Instead use a while loop
Updatable / Non Updatable View Names
For Views which are updatable, act as if they are a table.
This holds true for Updatable Partitioned Views.
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix with “VW_”
o Object: Required; usually related to the table(s) affected by the view
o Qualifier: Optional; additional descriptive words which help to clarify the purpose of the view.
o Example View Names are :
• vw_report_user_real_time
• vw_transcript_history
Trigger Names
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix with “TRG”
o Type: Required; depending on type of trigger, after or instead of. prefix with “A_” or “I_”
o Object: Required; usually the table being iterated over.
o Actions covered: Required; composite key of actions, “Upd”, “Ins”, “Del”
• Example Trigger Names:
o TRGA_CustomerInsUpdDe
o TRGA_ProductDel
o TRGI_AuthorUpd
• Note: Avoid the use of triggers where possible.
Primary Key Names
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix primary key with “PK_”
o TableName: Required; Table name of table being keyed
• Examples:
o PK_users
Index Names
Index names are unique within a table so it isn’t necessary to include the tablename in the index. When looking at execution plans it is helpful to have a hint about the columns being indexed
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix with “IX”
o Clustered: Required; if Clustered Index include “C”
o Unique: Required; if Unique Index include “U”
o Column Names: Required; Include the list of columns indexed, using underscores between the column names. For an index that covers all columns in the table, use the word All.
• Example Index Names:
o IXCU_user_ref (clustered unique)
o IXU_user_mgr (unique)
o IX_users_name_last_name_first (composite index)
o IXC_users_guid (clustered not unique)
Foreign Key Names
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix foreign key with “FK_”
o Reference Table Name(s): Required; Table name of table in the join, for which a unique index is on column(s) being linked. Where both have a unique index, such as linking key, order is optional
o Foreign Table Name(s): Required; Table name of table in the join, for there is not a unique index on the column(s) being linked.
• Example foreign key names:
o FK_users_user_type
o FK_users_users_status_local
Default Value Constraint Names
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix default value constraint with “DF_”
o TableName: Required; Table name
o ColumnName: Required; Column name
• Example foreign key names:
o DF_users_absent
Check Constraint Names
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix check constraint with “CK_”
o TableName: Required; Table name
o Integer: Required; Where the integer id is used to distinguish the check constraint from other check constraints on the same table.
• Example foreign key names:
o CK_users1
Alphanumeric characters only ([a-zA-Z0-9]) – In every case only alphanumeric characters (and some situations underscore) are allowed
General Rules
The following rules should apply to all database objects.
• Clear and unambiguous naming.
o The name should provide as much information as possible about an object and provide an obvious connection to references in project documentation. Choice of names should typically consider a name space much larger than a project—preferably the enterprise. A name uniquely identifies a database object; its definition should be consistent wherever the object is used. What might seem clear in a narrow context may lose meaning outside of that context. Saving keystrokes should never be used as a criterion in selecting a name.
• Abbreviations should be avoided.
o Only when length restrictions apply should they be permitted. When used, abbreviations should follow the abbreviation rules.
o Example :
--Correct
DECLARE @Counter int
--Avoid
DECLARE @C int
• Alphanumeric characters only ([a-zA-Z0-9]) – Do not use special characters; restrict names to alphanumeric characters, no space is allowed in object name:
o Example :
--Avoid
CREATE TABLE dbo.[User Information]
• System naming should be avoided. Do not use any prefix or object names that somehow links to system object. No DB object can be created under “SYS” schema and there are limitations on prefixes on Stored procedures too, Please check Stored Procedure section for more details.
• Use Upper case for all T-SQL constructs (except types).
o Example : SELECT MAX(MyField) FROM MyTable
• Use Lower case for all T-SQL types and usernames:
o Example : DECLARE @MyVariable int
Database Object Naming Rules
Summary:
Object Prefix Suffix Alpha Numeric Characters Notes
Tables x Use singular form: Example User, not Users
Linking Tables _Link x Formed from the Tables they are linking, Example: A Table joining User and Group would be UserGroupLink
Table Columns x
Primary Key PK_ x
Clustered Index IXC_ x
Unique Clustered Index IXCU_ x
Unique Index IXU_ x
Index IX_ x
XML Index XML_IX_ x
XML Columns x Use .net casing, no underscores
Constraints CK_ x
Default Value DF_ x
Foreign Keys FK_ x
Views VW_ x
Functions FN_ x
Stored Procedures PR_ x
Triggers (after) TRGA_ x
Triggers (instead) TRGI_ x
CTE (Common Table Expressions) CTE_ x
Schemas
• Use lowercase for schema names.
• Always alias database objects using the schema name, even if this is the default [dbo] schema
• This applies to both CREATE statements and when referencing objects in FROM, INSERT or UPDATE statements etc.
Table Names
• Prefixes are used to identify the table with relation to application modules as much as possible. Some of the most common prefixes are as :
• ANALYTICS_
• AUDIT_
• BILLING_
• CAREER_
• CERT_
• CMP_
• COMMENT_
• COMPASSES_
• CONNECT_
• CORP_
• DESIGNATION_
• DEVPLAN_
• EMAIL_
• EVALUATION_
• LCMS_
• LICENSE_
• LO_
• OU_
• PO_
• PROXY_
• QTI_
• REPORT_
• RESUME_
• REVIEW_
• SECURITY_
• SMP_
• SOAP_
• TALENT_
• TASK_
• USER_
• WAREHOUSE_
• Alphanumeric characters only
• Always assign schema name to UDO’s (User Define Object) when defining or referencing
• Example :
--Correct
CREATE TABLE dbo.MyTable (...)
--Avoid
CREATE TABLE MyTable (...)
• Use the Singular Form Example : User, not Users
• Example :
--Correct
CREATE TABLE dbo.Address
--Avoid
CREATE TABLE dbo.Addresses
--Correct
SELECT * FROM dbo.MyTable (...)
--Avoid
SELECT * FROM MyTable (...)
Linking Table Names
• Linking Tables should be the name of the two tables it is joining, suffixed with _Link. Eg a joining table on User and Group would be User_Group_Link
Column Names
• Alpha-numeric
• No Prefix
• Format:
use the following components in the order below;
o Table Name: Primary keys only; Tables names are used to prefix all columns in dotted format, so this is not necessarily. The exception is the primary key since this is used in foreign keys.
o Qualifier: Optional; Description, to clarify the meaning of the field. For example, if a product has two images, this would clarify the field, eg. FrontImage and RearImage
o Name: Required; This is a database independent “datatype” descriptor which is used to classify the type of data. Below is a common list of standard classifiers. The exception to this is a Boolean. This should be Prefixed with “Is” as this more positively represents the meaning o the value. Flag suffix is considered optional “Flag” or Example. IsEnabled or IsEnabledFlag
Classifier Description Suggested SQL Data Type
Address Street or mailing address data nvarchar
Age Chronological age in years int
Average Average; consider a computed column numeric
Amount Currency amount money
Code Non Database Identifier
Count
Data A field containing extensible data xml
Date Calendar date smalldatetime
Datetime Date including time datetime
Day Day of month (1 - 31) tinyint
Description Brief narrative description nvarchar(MAX)
Duration Length of time, eg minutes int
ID Unique identifier for something int
Image A graphic image, such as a bitmap varbinary(MAX)
Flag Not Required: Flag indicates a boolean indicator, where the Qualifier verb does not make it clear it is a verb. Examples of a Qualifier are: Is, Has, Uses. Eg IsEnabled bit
Month Month of year
Name Formal name nvarchar
Number
Percent Number expressed as a percent
Quantity A number of things any numerical
Rate Number expressed as a rate any numerical
Ratio A proportion, or expression of relationship in quantity, size, amount, etc. between two things any numerical
Sequence A numeric order field int
Text Freeform textual information nvarchar(MAX)
Time Time of day smalldatetime
Title Formal name of something nvarchar
Version Timestamp timestamp
Weight Weight measurement any numerical
XML A field containing xml data xml
Year Calendar year or julian year number
Stored Procedure Names
• Naming Format: use the following components in the order below;
o Object: Required; usually the table or combinations of tables it is affecting, followed by underscore.
o Action: Required; eg Save, Load, Get, Set, SetSingle, Search, Delete
o Qualifier: Optional; additional descriptive words which help to clarify the specific meaning of the stored procedure
o Return Type: Optional; Indicates the type of data return
• Example Stored Procedure Names:
o pr_cmp_adjustment_save
o pr_cmp_adjustment_delete
o pr_cmp_adjustment_get
o pr_cmp_adjustment_search
• Do not:
o Use special characters.
o Use stored procedure group numbers (e.g. myProc;1).
o Prefix names with “dt_” or “sp_” or “xp_” as those are reserved for procedures shipped by SQL Server.
• Always create scope when defining Procedures and multi statement functions.
o Example :
--Correct
CREATE PROCEDURE dbo.uspMyProcedure
AS
BEGIN
(...)
END
--Avoid
CREATE PROCEDURE dbo.uspMyProcedure
AS
(...)
• When joining table always identify all columns with aliases and always alias the AS keyword.
o Example :
--Correct
SELECT U.Surname,
A.Street
FROM dbo.[User] AS U
JOIN dbo.Address AS A ON U.AddressID = A.AddressID
--Avoid
SELECT U.Surname,
Street –-Missing alias
FROM Users U –-Missing AS
JOIN dbo.Address ON U.AddressID = dbo.Address.AddressID
• When defining procedures and functions, include a commented Test Harness. Declare used variables for usage in testing:
o Example :
--Correct
CREATE FUNCTION dbo.tvfMyFunction
(
@MyParameter int
)
AS
/* TEST HARNESS
DECLARE @MyParameter int
SET @MyParameter = 1
SELECT * FROM dbo.tvfMyFunction(@MyParameter)
*/
(...)
--Correct
CREATE PROCEDURE dbo.uspMyProcedure
(
@MyParameter int
)
AS
/* TEST HARNESS
DECLARE @MyParameter int
SET @MyParameter = 1
BEGIN TRAN
SELECT * FROM dbo.MyTable –-MyTable before operation
EXEC dbo.uspMyProcedure(@MyParameter)
SELECT * FROM dbo.MyTable –-MyTable after operation
ROLLBACK TRAN
*/
(...)
--Avoid
/* TEST HARNESS
SELECT * FROM dbo.tvfMyFunction(1) –-argument not declared
*/
• Always individually name fields in INSERT and UPDATE statements. Never use the * operator in such statements.
o Example :
--Correct
INSERT INTO dbo.[User] (FirstName, LastName)
VALUES (@FirstName, @LastName)
--Avoid
INSERT INTO dbo.[User]
VALUES (@FirstName, @LastName)
• Set the NOCOUNT state as the first statement in all Procedures where you don’t specifically need the count returned.
o Example :
--Correct
CREATE PROCEDURE dbo.uspMyProcedure (...)
AS
BEGIN
SET NOCOUNT ON
(...)
• Set ISOLATION LEVEL READ UNCOMMITTED for retrieving data procs. This option has the same effect as setting NOLOCK on all tables in all SELECT statements in a transaction. This is the least restrictive of the four isolation levels.
o Example :
--Correct
Select FirstName, LastName FROM dbo.[User] With (Nolock)
--Avoid
Select * FROM dbo.[User]
User Defined Functions (UDF) Names
• Naming Format: use the following components in the order below;
o Prefix: Required; “FN_”
o Object: Required; usually the table or combinations of tables it is affecting, followed by underscore.
o Action: Required; eg Get, Set, SetSingle, Search, Delete
o Qualifier: Optional; additional descriptive words which help to clarify the specific meaning of the stored procedure
o Return Type: Optional; Indicates the type of data return
• Example Function Names:
o fn_get_credential_name
Parameters and Parameters Type - Stored Procedure/UDFs
Example : Decalre @PageID int
Data types should be lowercase, like “int”, “nvarchar(100)”
Variables - Stored Procedure/UDFs
Example : Decalre @PageID int
Data types should be lowercase, like “int”, “nvarchar(100)”
Recursive (CTE or while loop)
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix with “CTE_”
o Object: Required; usually the table being iterated over.
o Substitute for a view when the general use of a view is not required; that is, you do not have to store the definition in metadata
• Example :
WITH CTE_Sales (SalesPersonID, NumberOfOrders, MaxDate)
AS
(
SELECT SalesPersonID, COUNT(*), MAX(OrderDate)
FROM Sales.SalesOrderHeader
GROUP BY SalesPersonID
)
SELECT E.EmployeeID, OS.NumberOfOrders, OS.MaxDate,
E.ManagerID, OM.NumberOfOrders, OM.MaxDate
FROM HumanResources.Employee AS E
JOIN CTE_Sales AS OS ON E.EmployeeID = OS.SalesPersonID
LEFT OUTER JOIN CTE_Sales AS OM ON E.ManagerID = OM.SalesPersonID
ORDER BY E.EmployeeID;
GO
• Note: Avoid the use of cursors where possible. Instead use a while loop
Updatable / Non Updatable View Names
For Views which are updatable, act as if they are a table.
This holds true for Updatable Partitioned Views.
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix with “VW_”
o Object: Required; usually related to the table(s) affected by the view
o Qualifier: Optional; additional descriptive words which help to clarify the purpose of the view.
o Example View Names are :
• vw_report_user_real_time
• vw_transcript_history
Trigger Names
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix with “TRG”
o Type: Required; depending on type of trigger, after or instead of. prefix with “A_” or “I_”
o Object: Required; usually the table being iterated over.
o Actions covered: Required; composite key of actions, “Upd”, “Ins”, “Del”
• Example Trigger Names:
o TRGA_CustomerInsUpdDe
o TRGA_ProductDel
o TRGI_AuthorUpd
• Note: Avoid the use of triggers where possible.
Primary Key Names
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix primary key with “PK_”
o TableName: Required; Table name of table being keyed
• Examples:
o PK_users
Index Names
Index names are unique within a table so it isn’t necessary to include the tablename in the index. When looking at execution plans it is helpful to have a hint about the columns being indexed
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix with “IX”
o Clustered: Required; if Clustered Index include “C”
o Unique: Required; if Unique Index include “U”
o Column Names: Required; Include the list of columns indexed, using underscores between the column names. For an index that covers all columns in the table, use the word All.
• Example Index Names:
o IXCU_user_ref (clustered unique)
o IXU_user_mgr (unique)
o IX_users_name_last_name_first (composite index)
o IXC_users_guid (clustered not unique)
Foreign Key Names
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix foreign key with “FK_”
o Reference Table Name(s): Required; Table name of table in the join, for which a unique index is on column(s) being linked. Where both have a unique index, such as linking key, order is optional
o Foreign Table Name(s): Required; Table name of table in the join, for there is not a unique index on the column(s) being linked.
• Example foreign key names:
o FK_users_user_type
o FK_users_users_status_local
Default Value Constraint Names
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix default value constraint with “DF_”
o TableName: Required; Table name
o ColumnName: Required; Column name
• Example foreign key names:
o DF_users_absent
Check Constraint Names
• Naming Format: use the following components in the order below;
o Prefix: Required; prefix check constraint with “CK_”
o TableName: Required; Table name
o Integer: Required; Where the integer id is used to distinguish the check constraint from other check constraints on the same table.
• Example foreign key names:
o CK_users1
Subscribe to:
Posts (Atom)