Tuesday, September 28, 2010

Identity


About Identity Columns
If you have worked with SQL Server, you are probably familiar with identity columns. These are equivalent to the "AutoNumber" columns in Access. The main purpose of these columns is to provide a primary key to the table when a primary key cannot be defined using other fields in the table.

These columns are like any other column except that their value is not inserted by the user, but by the system itself.
Syntax
IDENTITY [ ( seed , increment ) ]
Where:
seed - Is the value that is used for the very first row that is inserted into the table.
increment- Is the incremental value that is added to the previous identity value and thereby to get new value for the new row that is going to be added.
Note: You must specify both the seed and increment or neither. If neither is specified, the default is (1,1).

A few things you need to know about the identity columns:
·They should be of data type int, smallint, tinyint, decimal or numeric with scale 0.
·They cannot contain null values
·They cannot have any default values
·The identity increment is an integral value (1, -1, 5, etc.) and cannot contain decimals. Also, it cannot be 0.
·Identity Seed is 1 by default, and so is the Identity Increment. If you leave the seed field empty, it becomes 0.

 
Functions associated with IDENTITY column
·               @@IDENTITY
When a record is inserted into a table with an identity column, the function @@IDENTITY returns the last identity value that was inserted in the database.
Syntax
@@IDENTITY
 
I emphasize the phrase "last identity value" here because this may be different from the identity value of that particular table where the record was inserted.
Why? When a record is inserted and if there is any underlying trigger that modifies other tables, the value can be different. If a trigger adds a record into another table, which happens to have an identity column, @@IDENTITY will now return this new value instead.
 
·               Scope_IDENTITY
Returns the last IDENTITY value inserted into an IDENTITY column in the same scope. A scope is a stored procedure, function, or batch. Thus, two statements are in the same scope if they are in the same stored procedure, function, or batch. It may be more clear from the example below.
Syntax
SCOPE_IDENTITY()
 
·               IDENT_CURRENT
Returns the last identity value generated for a specified table in any session and any scope.
Syntax
IDENT_CURRENT('table_name')
 
·               IDENT_SEED
Returns the seed value specified during the creation of an identity column in a table that has an identity column.
Syntax
IDENT_SEED('table_name')
 
·               IDENT_INCR
Returns the increment value specified during the creation of an identity column in a table that has an identity column.
Syntax
IDENT_INCR('table_name')


Examples and Tips
 
Example
-- Consider the 2 Tables
CREATE TABLE Student(studId int IDENTITY(1,1), studName varchar(30))
CREATE TABLE Copy_Student(sid int IDENTITY(100,1))
GO

--Create trigger for insert on table Student
CREATE TRIGGER trgStudent ON Student FOR INSERT
AS
BEGIN
   INSERT INTO Copy_Student DEFAULT VALUES
END
GO

--Check The Tables
SELECT  *  FROM Student    --No records
SELECT  *  FROM Copy_Student --No records
GO
--Now do the following to check out the difference


INSERT INTO Student(studName) VALUES('Anjali Chelawat')

SELECT @@IDENTITY AS [IDENTITY]

--Returns the value 100, which was inserted by the trigger that is by the second insert statement.


SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY] 

--Returns the value 1, which was inserted by the Student table INSERT Statement before the trigger's insert statement.


SELECT IDENT_CURRENT('student') AS [IDENT_CURRENT]

--Returns last identity value inserted into Student.



SELECT IDENT_CURRENT('copy_student') AS [IDENT_CURRENT]

--Returns last identity value inserted into Copy_Student.


SELECT IDENT_INCR('student') AS [IDENT_INCR]

-- Returns the increment value of the identity column of the table Student. The value provided at the time of creation of the identity column


SELECT IDENT_SEED('student') AS [IDENT_SEED]

-- Returns the seed value of the identity column of the table Student. The value provided at the time of creation of the identity column


 
A Few Tips
·         Allowing inserts to identity columns:
 
If you are inserting data from some other source to a table with an identity column and you need to ensure you retain the identity values, you can temporarily allow inserts to the identity column. Without doing so explicitly you will receive an error if you attempt to insert a value into the identity column. For example, if I have a table named MYTABLE and I want to allow inserts into the identity column, I can execute the following:
Syntax
set identity_ insert  table_name on
 
Once you execute the command you will be able to insert values into the table's identity column. This will stay in effect in until you turn it off by executing the following:
 

Syntax

 
set identity_insert table_name off
 
Note: Be aware that at any time, only a single table in a session can have the identity_insert set to on.  If you attempt to enable this for a table and another table already has this enabled, you will receive an error and will not be able to do so until you first turn this off for the other table. Also, if the value used for the identity is larger than the current identity value then the new value will be used for the identity seed for the column.  


·         Reseeding the identity value:

You can reseed the identity value, that is, to have the identity values reset or start at a new predefined value by using DBCC CHECKIDENT.  For example, if I have a table named MYTABLE and I want to reseed the identity column to 30 I would execute the following:
 
dbcc checkident (‘table_name, reseed, 30)
 
If you wanted to reseed the table to start with an identity of 1 with the next insert then you would reseed the table's identity to 0.  The identity seed is what the value is currently at, meaning that the next value will increment the seed and use that.  However, one thing to keep in mind is that if you set the identity seed below values that you currently have in the table, that you will violate the identity column's uniqueness constraint as soon as the values start to overlap.  The identity value will not just “skip” values that already exist in the table.


 
Points To Remember
·   IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.
·   @@IDENTITY returns the last identity value generated for any table in the current session, across all scopes.
·   SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope.

SQL Server – DBCC Commands

DBCC (Database consistency checker) are used to check the consistency of the databases. The DBCC commands are most useful for performance and trouble shooting exercises.
I have listed down and explained all the DBCC commands available in SQL Server 2005, with examples.
The DBCC Commands broadly falls into four categories:
Maintenance
Informational
Validation
Miscellaneous
Maintenance Commands
Performs maintenance tasks on a database, index, or filegroup.
1. CLEANTABLE – Reclaims space from the dropped variable-length columns in tables or index views.
DBCC CLEANTABLE (‘AdventureWorks’,'Person.Contact’,0)2. DBREINDEX – Builds one or more indexes for the table in the specified database. (Will be removed in the future version, use ALTER INDEX instead)
USE AdventureWorks
DBCC DBREINDEX (‘Person.Contact’,'PK_Contact_ContactID’,80)3. DROPCLEANBUFFERS – Removes all clean buffers from buffer pool.
DBCC DROPCLEANBUFFERS4. FREEPROCCACHE – Removes all elements from the procedure cache
DBCC FREEPROCCACHE5. INDEXDEFRAG – Defragments indexes of the specified table or view.
DBCC INDEXDEFRAG (‘AdventureWorks’, ‘Person.Address’, PK_Address_AddressID)6. SHRINKDATABASE – Shrinks the size of the data and log files in the specified database
DBCC SHRINKDATABASE (‘AdventureWorks‘, 10)7. SHRINKFILE – Shrinks the size of the specified data or log file for the current database or empties a file by moving the data from the specified file to other files in the same filegroup, allowing the file to be removed from the database.
USE AdventureWorks;
– Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (AdventureWorks_Log, 1)8. UPDATEUSAGE – Reports and corrects pages and row count inaccuracies in the catalog views.
DBCC UPDATEUSAGE (AdventureWorks)Informational Commands
Performs tasks that gather and display various types of information.
1. CONCURRENCYVIOLATION – is maintained for backward compatibility. It runs but returns no data.
DBCC CONCURRENCYVIOLATION2. INPUTBUFFER – Displays the last statement sent from a client to an instance of Microsoft SQL Server 2005.
DBCC INPUTBUFFER (52)3. OPENTRAN – Displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the specified database.
DBCC OPENTRAN;4. OUTPUTBUFFER – Returns the current output buffer in hexadecimal and ASCII format for the specified session_id.
DBCC OUTPUTBUFFER (52)5. PROCCACHE – Displays information in a table format about the procedure cache.
DBCC PROCCACHE6. SHOW_STATISTICS – Displays the current distribution statistics for the specified target on the specified table
USE AdventureWorks
DBCC SHOW_STATISTICS (‘Person.Address’, AK_Address_rowguid)7. SHOWCONTIG – Displays fragmentation information for the data and indexes of the specified table or view.
USE AdventureWorks
DBCC SHOWCONTIG (‘HumanResources.Employee’);8. SQLPERF – Provides transaction log space usage statistics for all databases. It can also be used to reset wait and latch statistics.
DBCC SQLPERF(LOGSPACE)9. TRACESTATUS – Displays the status of trace flags.
DBCC TRACESTATUS(-1)10. USEROPTIONS – Returns the SET options active (set) for the current connection.
DBCC USEROPTIONSValidation Commands
Performs validation operations on a database, table, index, catalog, filegroup, or allocation of database pages.
1. CHECKALLOC – Checks the consistency of disk space allocation structures for a specified database.
DBCC CHECKALLOC (AdventureWorks)2. CHECKCATALOG – Checks for catalog consistency within the specified database.
DBCC CHECKCATALOG (AdventureWorks)3. CHECKCONSTRAINTS – Checks the integrity of a specified constraint or all constraints on a specified table in the current database.
DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS4. CHECKDB – Checks the logical and physical integrity of all the objects in the specified database.
DBCC CHECKDB (AdventureWorks)5. CHECKFILEGROUP – Checks the allocation and structural integrity of all tables and indexed views in the specified filegroup of the current database.
USE AdventureWorks
DBCC CHECKFILEGROUP6. CHECKIDENT – Checks the current identity value for the specified table and, if it is needed, changes the identity value.
USE AdventureWorks;
DBCC CHECKIDENT (‘HumanResources.Employee’)7. CHECKTABLE – Checks the integrity of all the pages and structures that make up the table or indexed view.
USE AdventureWorks;
DBCC CHECKTABLE (‘HumanResources.Employee’)Miscellaneous Commands
Performs miscellaneous tasks such as enabling trace flags or removing a DLL from memory.
1. dllname (FREE) – Unloads the specified extended stored procedure DLL from memory.
DBCC xp_sample (FREE)2. TRACEOFF – Disables the specified trace flags.
DBCC TRACEOFF (3205)3. HELP – Returns syntax information for the specified DBCC command.
– List all the DBCC commands
DBCC HELP (‘?’)
– Show the Syntax for a given DBCC commnad
DBCC HELP (‘checkcatalog’)4. TRACEON – Enables the specified trace flags.
DBCC TRACEON (3205)

SQL Server 2005 Backup Error Messages

MSSQL 2005 Backup or its related Error Messages
Severity level 10 messages are informational and indicate problems caused by mistakes in the information you have entered. Severity levels from 11 through 16 are generated by the user, and can be corrected by the user.
Severity levels from 17 through 25 indicate software or hardware errors (Please find the below update error messages).
We have to inform the system administrator whenever problems that generate errors with severity levels 17 and higher than it. The system administrator must resolve these errors and track their frequency. When a level 17, 18, or 19 errors occur, we can continue working, although we might not be able to execute a particular statement.
Error Messages
select message_id, severity, [text] from sys.messages where language_id = 1033 and severity <> 10 and  [text] like ‘%backup%’
Msg IdSeverityError Message
2062211Replication database option -sync with backup- cannot be set on the publishing database because the database is in Simple Recovery mode_
141116The remote copy of database -_*ls has not had enough log backups applied to roll forward all of its files to a common point in time_
147516Database mirroring cannot be enabled because the -_*ls database may have bulk logged changes that have not been backed up_ The last log backup on the principal must be restored on the mirror_
147816The mirror database, -_*ls, has insufficient transaction log data to preserve the log backup chain of the principal database_  This may happen if a log backup from the principal database has not been taken or has not been restored on the mirror database_
183316File _ls- cannot be reused until after the next BACKUP LOG operation_
193116The SQL statement cannot be executed because filegroup __*ls- is offline_ Use the sys_database_files or sys_master_files catalog view to determine the state of the files in this filegroup and then restore the offline file(s) from backup_
250516The device __*ls- does not exist_ Use sys_backup_devices to show available devices_
251516Page -S_PGID, object ID -d, index ID -d, partition ID -I64d, alloc unit ID -I64d type -_*ls) has been modified but is not marked modified in the differential backup bitmap_
251616Repair has invalidated the differential bitmap for database -_*ls_ The differential backup chain is broken_ You must perform a full database backup before you can perform a differential backup_
251716Bulk-logging has been turned on for database -_*ls_ To ensure that all data has been secured, run backup log operations again_
300216Cannot BACKUP or RESTORE a database snapshot_
300416The primary filegroup cannot be backed up as a file backup because the database is using the SIMPLE recovery model_ Consider taking a partial backup by specifying READ_WRITE_FILEGROUPS_
300616The differential backup is not allowed because it would be based on more than one base backup_ Multi-based differential backups are not allowed in the simple recovery model, and are never allowed for partial differential backups_
300716The backup of the file or filegroup -ls is not permitted because it is not online_ BACKUP can be performed by using the FILEGROUP or FILE clauses to restrict the selection to include only online data_
300816The specified device type is not supported for backup mirroring_
300916Could not insert a backup or restore history/detail record in the msdb database_ This may indicate a problem with the msdb database_ The backup/restore operation was still successful_
301016Invalid backup mirror specification_ All mirrors must have the same number of members_
301116All backup devices must be of the same general class (for example, DISK and TAPE)_
301616Backup of file _ls- is not permitted because it contains pages subject to an online restore sequence_ Complete the restore sequence before taking the backup, or restrict the backup to exclude this file_
302116Cannot perform a backup or restore operation within a transaction_
302316Backup and file manipulation operations (such as ALTER DATABASE ADD FILE) on a database must be serialized_ Reissue the statement after the current backup or file manipulation operation is completed_
302416You can only perform a full backup of the master database_ Use BACKUP DATABASE to back up the entire master database_
303316BACKUP DATABASE cannot be used on a database opened in emergency mode_
303516Cannot perform a differential backup for database -ls, because a current database backup does not exist_ Perform a full database backup by reissuing BACKUP DATABASE, omitting the WITH DIFFERENTIAL option_
303816The file name -ls is invalid as a backup device name_ Reissue the BACKUP statement with a valid file name_
303916Cannot perform a differential backup for file _ls- because a current file backup does not exist_ Reissue BACKUP DATABASE omitting the WITH DIFFERENTIAL option_
304116BACKUP failed to complete the command -_*ls_ Check the backup application log for detailed messages_
304316BACKUP _ls- detected an error on page (-d:-d) in file _ls-_
304416Invalid zero-length device name_ Reissue the BACKUP statement with a valid device name_
304516Differential BACKUP or RESTORE is not supported on the FAT file system_ The path -_*ls is not usable_
304616Inconsistent metadata has been encountered_ The only possible backup operation is a tail-log backup using the WITH CONTINUE_AFTER_ERROR or NO_TRUNCATE option_
304716The BackupDirectory registry key is not configured correctly_ This key should specify the root path where disk backup files are stored when full path names are not provided_ This path is also used to locate restart checkpoint files for RESTORE_
304816BACKUP LOG WITH TRUNCATE_ONLY cannot operate on database _ls- because it is configured for database mirroring_
304916BACKUP detected corruption in the database log_ Check the errorlog for more information_
305016SQL Server could not send the differential information for database file _ls

System Databases In Sql Server 2005

SQL Server System Databases
Master
Purpose – Core system database to manage the SQL Server instance. In SQL Server 2005, the Master database is the logical repository for the system objects residing in the sys schema. In SQL Server 2000 and previous editions of SQL Server, the Master database physically stored all of the system objects.
Prominent Functionality
Per instance configurations
Databases residing on the instance
Files for each database
Logins
Linked\Remote servers
Endpoints
Additional Information
The first database in the SQL Server startup process
In SQL Server 2005, needs to reside in the same directory as the Resource database
Resource
Purpose – The Resource database is responsible for physically storing all of the SQL Server 2005 system objects. This database has been created to improve the upgrade and rollback of SQL Server system objects with the ability to overwrite only this database.
Prominent Functionality
System object definition
Additional Information
Introduced in SQL Server 2005 to help manage the upgrade and rollback of system objects
Prior to SQL Server 2005 the system related data was stored in the master database
Read-only database that is not accessible via the SQL Server 2005 tool set
The database ID for the Resource database is 32767
The Resource database does not have an entry in master.sys.databases
TempDB
Purpose – Temporary database to store temporary tables (#temptable or ##temptale), table variables, cursors, work tables, row versioning, create or rebuild indexes sorted in TempDB, etc. Each time the SQL Server instance is restarted all objects in this database are destroyed, so permanent objects cannot be created in this database.
Prominent Functionality
Manage temporary objects listed in the purpose above
Additional Information
Each time a SQL Server instance is rebooted, the TempDB database is reset to its original state
Model
Purpose – Template database for all user defined databases
Prominent Functionality
Objects
Columns
Users
Additional Information
User defined tables, stored procedures, user defined data types, etc can be created in the Model database and will exist in all future user defined databases
The database configurations such as the recovery model for the Model database are applied to future user defined databases
MSDB
Purpose – Primary database to manage the SQL Server Agent configurations
Prominent Functionality
SQL Server Agent Jobs, Operators and Alerts
DTS Package storage in SQL Server 7.0 and 2000
SSIS Package storage in SQL Server 2005
Additional Information
Provides some of the configurations for the SQL Server Agent service
For the SQL Server 2005 Express edition installations, even though the SQL Server Agent service does not exist, the instance still has the MSDB database
Distribution
Purpose – Primary data to support SQL Server replication
Prominent Functionality
Database responsible for the replication meta data
Supports the data for transaction replication between the publisher and subscriber(s)
ReportServer
Purpose – Primary database for Reporting Services to store the meta data and object definitions
Prominent Functionality
Reports security
Job schedules and running jobs
Report notifications
Report execution history
ReportServerTempDB
Purpose – Temporary storage for Reporting Services
Prominent Functionality
Session information
Cache

Friday, September 24, 2010

Newid() in Sql Server

Use SQL NEWID in SQL Functions as SQL Random Generator

SQL NewID function is used for selecting random row from a resultset in SQL Server databases. Using with TOP N keyword in SELECT statements where SQL NEWID is in the ORDER BY statement, random records are selected from a table or from a set of rows. "SELECT TOP 1 FullName FROM Customers ORDER BY NEWID ()" is a sample sql NEWID usage.
You can find a more complex use of sql NEWID in an other tsql example valid for MS SQL Server 2005 and SQL Server 2008 database instances at SELECT TOP N Random Rows For Each Category in a SQL Table.
SQL Server administrators and T-SQL developers frequently require SQL functions that return random row, random number, etc but something which is randomized. Since user defined sql functions are easy to use in sql SELECT statements, it is useful to move MSSQL NEWID functionality into sql functions. But there is a problem here. It is not allowed to use undetermenistic functions in SQL Server functions. Let me explain.
Let's try to create sample function whose source code is shown below.
CREATE FUNCTION GetRandomProduct()
RETURNS nvarchar(50)
AS
BEGIN
RETURN (SELECT TOP 1 Name FROM Production.Product ORDER BY NewId())
END
GO


When you execute the above sql CREATE FUNCTION script, SQL Server will throw the following sql exception message.
Msg 443, Level 16, State 1, Procedure GetRandomProduct, Line 6
Invalid use of a side-effecting operator 'newid' within a function.


You can see from the message itself that tsql NEWID operator is not allowed for a direct use in sql functions.
Let me share a work around with you sql developers and administrators which will let you use NEWID in sql function. This work-around will enable us to build sql functions that row random rows from sql tables. So it will be possible to create random row generator or random string generator, etc.

Here is the t-sql trick which will enable developers to use sql NEWId in sql functions.
First create a sql VIEW object using CREATE VIEW command. The sql script of GetNewId view is given below. As you can see the GetNewId sql view only returns single row with single NEWId() uniqueidentifier.
CREATE VIEW dbo.GetNewID
AS
SELECT NewId() AS [NewID]
GO


In the below T-SQL function, developers will notice that ORDER BY NEWID() is replaced with the newly created sql view. Now the ORDER BY clause is in the form "ORDER BY (SELECT [NewId] FROM GetNewID)"
CREATE FUNCTION GetRandomProduct()
RETURNS nvarchar(50)
AS
BEGIN
RETURN (
  SELECT TOP 1 Name
  FROM Production.Product
  ORDER BY (SELECT [NewId] FROM GetNewID)
)
END
GO


And if you execute the sql CREATE FUNCTION statement, you will see that the user defined sql function GetRandom bla bla bla is created successfully without any sql error.
Now let's use the NEWID in sql random function in a tsql example code.
SELECT dbo.GetRandomProduct()
Here is an other example sql codes which returns a random product for each employee using sample MS SQL Server 2008 AdventureWorks database.
SQL Server NEWID operator is working successfully in this sql function SELECT statement, too.
SELECT
  e.EmployeeID, c.FirstName, c.LastName,
  dbo.GetRandomProduct() AS [Random Prize]
FROM HumanResources.Employee e
INNER JOIN Person.Contact c ON c.ContactID = e.ContactID


Below is the screenshot where you can see the result of the sql random function. The most important point in this sql function script is the use tsql NEWID view. I named this sql view as dbo.GetNewID.
use-random-function-newid-in-sql-function
As summary, although sql NEWId operator is not allowed for use in sql functions, by using sql NEWID() operator in a VIEW which is called by the SQL function random rows can be selected easily.

SQL SERVER – Deterministic Functions and Nondeterministic Functions

Deterministic functions always returns the same output result all the time it is executed for same input values. i.e. ABS, DATEDIFF, ISNULL etc.
Nondeterministic functions may return different results each time they are executed. i.e. NEWID, RAND, @@CPU_BUSY etc. Functions that call extended stored procedures are nondeterministic. User-defined functions that create side effects on the database are not recommended.

Wednesday, September 22, 2010

Find Relationship of Foreign Key and Primary Key using T-SQL

--option 1SELECT PK.TABLE_NAME,PK.CONSTRAINT_NAME ,FK.CONSTRAINT_NAME FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS PKINNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS FKON PK.CONSTRAINT_NAME=FK.UNIQUE_CONSTRAINT_NAME---option 2SELECT f.name AS ForeignKey,SCHEMA_NAME(f.SCHEMA_ID) SchemaName,OBJECT_NAME(f.parent_object_id) AS TableName,COL_NAME(fc.parent_object_id,fc.parent_column_id) AS ColumnName,SCHEMA_NAME(o.SCHEMA_ID) ReferenceSchemaName,OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,COL_NAME(fc.referenced_object_id,fc.referenced_column_id) AS ReferenceColumnNameFROM

sys.foreign_keys AS fINNER JOIN sys.foreign_key_columns AS fcINNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_idON f.OBJECT_ID = fc.constraint_object_id--OPTION 3SELECT t.name AS [Table],c.name AS [Column]FROM
SYS.TABLES tINNER JOIN SYS.SYSCOLUMNS c ONc.id = t.object_id-- Join on foreign key columnsLEFT JOIN SYS.FOREIGN_KEY_COLUMNS fkc ON(fkc.parent_object_id = t.object_idAND c.colid = fkc.parent_column_id)OR (fkc.referenced_object_id = t.object_idAND c.colid = fkc.referenced_column_id)-- Join on primary key columnsLEFT JOIN SYS.INDEXES i ONi.object_id = t.object_id
and i.is_primary_key = 1LEFT JOIN SYS.INDEX_COLUMNS ic ONic.object_id = t.object_id
AND ic.index_id = i.index_idAND ic.column_id = c.colidWHEREt
.is_ms_shipped = 0AND (c.name LIKE '%ID' OR c.name LIKE '%Code')AND(fkc.constraint_object_id IS NULL -- Not part of a foreign keyAND ic.object_id IS NULL -- Not part of a primary key)
    While searching for how to find Primary Key and Foreign Key relationship using T-SQL, I came across my own blog article written earlier SQL SERVER – 2005 – Find Tables With Foreign Key Constraint in Database. It is really handy script and not found written on line anywhere. This is one really unique script and must be bookmarked. There may be situations when there is need to find out on relationship between Primary Key and Foreign Key.
   I have modified my previous script to add schema name along with table name. It would be really great if any of you can improve on this script.


                                 (or)

SELECT PK.TABLE_NAME,PK.CONSTRAINT_NAME ,FK.CONSTRAINT_NAME FROM
   INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK       INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS FKON

     PK.CONSTRAINT_NAME=FK.UNIQUE_CONSTRAINT_NAME

SELECT f.name AS ForeignKey,SCHEMA_NAME(f.SCHEMA_ID) SchemaName,OBJECT_NAME(f.parent_object_id) AS TableName,COL_NAME(fc.parent_object_id,fc.parent_column_id) AS ColumnName,SCHEMA_NAME(o.SCHEMA_ID) ReferenceSchemaName,OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,COL_NAME(fc.referenced_object_id,fc.referenced_column_id) ASReferenceColumnNameFROM sys.foreign_keys AS fINNER JOIN sys.foreign_key_columns AS fcINNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_idON f.OBJECT_ID = fc.constraint_object_id