Sunday, November 21, 2010

sp_fkeys v/s sp_foreignkeys

sp_fkeys and sp_foreignkeys are two system procedures available in SQL Server giving information about foreignkeys. Then what exactly is difference between them? For this lets see the syntax of both.

sp_fkeys
---------------
sp_fkeys @pktable_name,     @pktable_owner,     @pktable_qualifier,     @fktable_name,     @fktable_owner,     @fktable_qualifier 
If you see from above sp_fkeys accept the above parameters and returns the  information on foreign keys.  All parameters are optional. If you pass only  the pk table information, it lists all the tables where this pk column   is used as a foreign key. Alternatively if you pass only fk table  information it returns details of all tables related  to passed table in  pk fk relationship
Now lets see the syntax for sp_foreignkeys
sp_foreignkeys  @table_server,    @pktab_name,     @pktab_schema,    @pktab_catalog ,    @fktab_name,    @fktab_schema ,    @fktab_catalog 
As you see from above the first parameter is table server name.  This is  because sp_foreignkeys retrieves details of foreign key  relationships  from linked server. so we need to pass the linked server name as first  parameter for sp_foreignkeys. the other parameters have exactly same  meaning as in sp_fkeys.Similarly sp_pkeys and sp_primarykeys procedures differ in same way.