<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
		>
<channel>
	<title>Comments on: SQL SERVER &#8211; Puzzle &#8211; Write Script to Generate Primary Key and Foreign Key</title>
	<atom:link href="http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/</link>
	<description>Personal Notes of Pinal Dave</description>
	<lastBuildDate>Fri, 10 Feb 2012 04:45:32 +0000</lastBuildDate>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
	<item>
		<title>By: kevin</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-85024</link>
		<dc:creator><![CDATA[kevin]]></dc:creator>
		<pubDate>Mon, 23 Aug 2010 18:46:50 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-85024</guid>
		<description><![CDATA[Oh , and per the first few responses to this. you cannot, as far as I can see, generate creation scripts for primary keys from management studio. Maybe I am missing something, but you should be able to.]]></description>
		<content:encoded><![CDATA[<p>Oh , and per the first few responses to this. you cannot, as far as I can see, generate creation scripts for primary keys from management studio. Maybe I am missing something, but you should be able to.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: kevin</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-85023</link>
		<dc:creator><![CDATA[kevin]]></dc:creator>
		<pubDate>Mon, 23 Aug 2010 18:45:14 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-85023</guid>
		<description><![CDATA[I clicked on John Paul&#039;s link to the script and get a display page error.]]></description>
		<content:encoded><![CDATA[<p>I clicked on John Paul&#8217;s link to the script and get a display page error.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: kevin</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-84998</link>
		<dc:creator><![CDATA[kevin]]></dc:creator>
		<pubDate>Mon, 23 Aug 2010 13:57:39 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-84998</guid>
		<description><![CDATA[so.....is there a reliable script to create all primary keys?]]></description>
		<content:encoded><![CDATA[<p>so&#8230;..is there a reliable script to create all primary keys?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: atul gupte</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-56401</link>
		<dc:creator><![CDATA[atul gupte]]></dc:creator>
		<pubDate>Sun, 04 Oct 2009 11:00:17 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-56401</guid>
		<description><![CDATA[very good information on sql server]]></description>
		<content:encoded><![CDATA[<p>very good information on sql server</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: John Paul Cook</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-55959</link>
		<dc:creator><![CDATA[John Paul Cook]]></dc:creator>
		<pubDate>Thu, 17 Sep 2009 23:09:51 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-55959</guid>
		<description><![CDATA[Pinal,

I wrote a script to create all foreign keys:

http://sqlblog.com/blogs/john_paul_cook/archive/2009/09/17/script-to-create-all-foreign-keys.aspx]]></description>
		<content:encoded><![CDATA[<p>Pinal,</p>
<p>I wrote a script to create all foreign keys:</p>
<p><a href="http://sqlblog.com/blogs/john_paul_cook/archive/2009/09/17/script-to-create-all-foreign-keys.aspx" rel="nofollow">http://sqlblog.com/blogs/john_paul_cook/archive/2009/09/17/script-to-create-all-foreign-keys.aspx</a></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: pinaldave</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-55952</link>
		<dc:creator><![CDATA[pinaldave]]></dc:creator>
		<pubDate>Thu, 17 Sep 2009 17:09:52 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-55952</guid>
		<description><![CDATA[Sir,

I should go over it tomorrow and with due credit will publish your link in next week.

kind Regards,
Pinal]]></description>
		<content:encoded><![CDATA[<p>Sir,</p>
<p>I should go over it tomorrow and with due credit will publish your link in next week.</p>
<p>kind Regards,<br />
Pinal</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: John Paul Cook</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-55951</link>
		<dc:creator><![CDATA[John Paul Cook]]></dc:creator>
		<pubDate>Thu, 17 Sep 2009 16:58:12 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-55951</guid>
		<description><![CDATA[Hi Pinal,

I updated my script and added code to handle ascending/descending sort order and to incorporate a suggestion from a reader.

http://sqlblog.com/blogs/john_paul_cook/archive/2009/09/16/script-to-create-all-primary-keys.aspx]]></description>
		<content:encoded><![CDATA[<p>Hi Pinal,</p>
<p>I updated my script and added code to handle ascending/descending sort order and to incorporate a suggestion from a reader.</p>
<p><a href="http://sqlblog.com/blogs/john_paul_cook/archive/2009/09/16/script-to-create-all-primary-keys.aspx" rel="nofollow">http://sqlblog.com/blogs/john_paul_cook/archive/2009/09/16/script-to-create-all-primary-keys.aspx</a></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: pinaldave</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-55946</link>
		<dc:creator><![CDATA[pinaldave]]></dc:creator>
		<pubDate>Thu, 17 Sep 2009 14:57:30 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-55946</guid>
		<description><![CDATA[Hi John Paul Cook,

Excellent script and your blog is one very good read always.

Kind Regards,
Pinal]]></description>
		<content:encoded><![CDATA[<p>Hi John Paul Cook,</p>
<p>Excellent script and your blog is one very good read always.</p>
<p>Kind Regards,<br />
Pinal</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: John Paul Cook</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-55930</link>
		<dc:creator><![CDATA[John Paul Cook]]></dc:creator>
		<pubDate>Thu, 17 Sep 2009 04:45:35 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-55930</guid>
		<description><![CDATA[Hi Pinal,

I needed to script primary key creation today at work, so I wrote this script:

http://sqlblog.com/blogs/john_paul_cook/archive/2009/09/16/script-to-create-all-primary-keys.aspx

Comparing it to the submissions on your site, I see that I didn&#039;t consider a descending primary key - we don&#039;t have those in the applications I work on.

You have some good submissions, although most people overlooked using brackets in case the object name has embedded spaces. Also, nobody considered that a primary key could be nonclustered. That&#039;s yet another reason to use the sys metadata views instead of INFORMATION_SCHEMA. It is an anachronistic myth that INFORMATION_SCHEMA views are better or more proper. All too often INFORMATION_SCHEMA views don&#039;t provide enough detail to finish the job.]]></description>
		<content:encoded><![CDATA[<p>Hi Pinal,</p>
<p>I needed to script primary key creation today at work, so I wrote this script:</p>
<p><a href="http://sqlblog.com/blogs/john_paul_cook/archive/2009/09/16/script-to-create-all-primary-keys.aspx" rel="nofollow">http://sqlblog.com/blogs/john_paul_cook/archive/2009/09/16/script-to-create-all-primary-keys.aspx</a></p>
<p>Comparing it to the submissions on your site, I see that I didn&#8217;t consider a descending primary key &#8211; we don&#8217;t have those in the applications I work on.</p>
<p>You have some good submissions, although most people overlooked using brackets in case the object name has embedded spaces. Also, nobody considered that a primary key could be nonclustered. That&#8217;s yet another reason to use the sys metadata views instead of INFORMATION_SCHEMA. It is an anachronistic myth that INFORMATION_SCHEMA views are better or more proper. All too often INFORMATION_SCHEMA views don&#8217;t provide enough detail to finish the job.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: shekhar sinha,Guwahati, Assam, India</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54906</link>
		<dc:creator><![CDATA[shekhar sinha,Guwahati, Assam, India]]></dc:creator>
		<pubDate>Mon, 17 Aug 2009 04:23:36 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54906</guid>
		<description><![CDATA[Dear Sir,

         I hv a pleasure to mail to you.

Still I&#039;m not satisfied.

Shekhar Sinha, Guwahati, Assam , India]]></description>
		<content:encoded><![CDATA[<p>Dear Sir,</p>
<p>         I hv a pleasure to mail to you.</p>
<p>Still I&#8217;m not satisfied.</p>
<p>Shekhar Sinha, Guwahati, Assam , India</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: manu</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54870</link>
		<dc:creator><![CDATA[manu]]></dc:creator>
		<pubDate>Sat, 15 Aug 2009 03:55:29 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54870</guid>
		<description><![CDATA[-- Get all existing primary keys
DECLARE cPK CURSOR FOR
   SELECT TABLE_NAME, CONSTRAINT_NAME
   FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
   WHERE constraint_type=&#039;PRIMARY KEY&#039;
   ORDER BY TABLE_NAME

DECLARE @PkTable SYSNAME
DECLARE @PkName SYSNAME

-- Loop through all the primary keys
OPEN cPK
FETCH NEXT FROM cPK INTO @PkTable, @PkName
WHILE (@@FETCH_STATUS = 0)
BEGIN
   DECLARE @PKSQL NVARCHAR(4000) SET @PKSQL = &#039;&#039;
   SET @PKSQL = &#039;ALTER TABLE &#039; + @PkTable + &#039; ADD CONSTRAINT &#039; + @PkName + &#039; PRIMARY KEY CLUSTERED (&#039;

   -- Get all columns for the current primary key
   DECLARE cPKColumn CURSOR FOR
      SELECT COLUMN_NAME 
      FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
      WHERE TABLE_NAME = @PkTable AND CONSTRAINT_NAME = @PkName
      ORDER BY ORDINAL_POSITION
   OPEN cPKColumn

   DECLARE @PkColumn SYSNAME
   DECLARE @Order SYSNAME	
   DECLARE @Index varchar(max)		
   DECLARE @PkFirstColumn BIT SET @PkFirstColumn = 1
   -- Loop through all columns and append the sql statement
   FETCH NEXT FROM cPKColumn INTO @PkColumn
   WHILE (@@FETCH_STATUS = 0)
   BEGIN
      IF (@PkFirstColumn = 1)
         SET @PkFirstColumn = 0
      ELSE
         SET @PKSQL = @PKSQL + &#039;, &#039;
	  Select @Order=Case is_descending_key when 0 then &#039; ASC&#039; ELSE &#039; DESC &#039; END 
      from sys.index_columns ic join sys.columns c
      on ic.index_column_id=c.column_id
	  and c.name=@PkColumn
      SET @PKSQL = @PKSQL + @PkColumn + @Order
--      print charindex(&#039;ASC,&#039;,@pksql)
      FETCH NEXT FROM cPKColumn INTO @PkColumn
      END
      Select @Index=&#039;) WITH &#039;+&#039;(PAD_INDEX =&#039;+CASE is_padded when 0 then &#039;OFF&#039; ELSE &#039;ON&#039; END+
					&#039;&#039;+&#039;, STATISTICS_NORECOMPUTE =&#039;+CASE no_recompute when 0 then &#039;OFF&#039; ELSE &#039;ON&#039; END+
					&#039;&#039;+&#039;, SORT_IN_TEMPDB =&#039;+CASE is_padded when 0 then &#039;OFF&#039; ELSE &#039;ON&#039; END+
					&#039;&#039;+&#039;, IGNORE_DUP_KEY =&#039;+CASE is_padded when 0 then &#039;OFF&#039; ELSE &#039;ON&#039; END+
					&#039;&#039;+&#039;, ONLINE =&#039;+CASE is_padded when 0 then &#039;OFF&#039; ELSE &#039;ON&#039; END+
					&#039;&#039;+&#039;, ALLOW_ROW_LOCKS =&#039;+CASE ALLOW_ROW_LOCKS when 0 then &#039;OFF&#039; ELSE &#039;ON&#039; END+
					&#039;&#039;+&#039;, ALLOW_PAGE_LOCKS =&#039;+CASE ALLOW_PAGE_LOCKS when 0 then &#039;OFF)&#039; ELSE &#039;ON)&#039; END
					  +&#039; ON &#039; +&#039;[&#039;+fg.name+&#039;]&#039;		
      from sys.indexes i join sys.stats s
      on i.name=s.name
	  join sys.filegroups fg
      on fg.data_space_id=i.data_space_id
      and i.name=@PkName
      SET @PKSQL = @PKSQL+@index


   CLOSE cPKColumn
   DEALLOCATE cPKColumn

   -- Print the primary key statement
   PRINT @PKSQL

   FETCH NEXT FROM cPK INTO @PkTable, @PkName
END
CLOSE cPK
DEALLOCATE cPK



Pinal, please try the above script for scripting out primary keys at database level and let me know where you think it needs amendment.


Manu]]></description>
		<content:encoded><![CDATA[<p>&#8211; Get all existing primary keys<br />
DECLARE cPK CURSOR FOR<br />
   SELECT TABLE_NAME, CONSTRAINT_NAME<br />
   FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS<br />
   WHERE constraint_type=&#8217;PRIMARY KEY&#8217;<br />
   ORDER BY TABLE_NAME</p>
<p>DECLARE @PkTable SYSNAME<br />
DECLARE @PkName SYSNAME</p>
<p>&#8211; Loop through all the primary keys<br />
OPEN cPK<br />
FETCH NEXT FROM cPK INTO @PkTable, @PkName<br />
WHILE (@@FETCH_STATUS = 0)<br />
BEGIN<br />
   DECLARE @PKSQL NVARCHAR(4000) SET @PKSQL = &#8221;<br />
   SET @PKSQL = &#8216;ALTER TABLE &#8216; + @PkTable + &#8216; ADD CONSTRAINT &#8216; + @PkName + &#8216; PRIMARY KEY CLUSTERED (&#8216;</p>
<p>   &#8212; Get all columns for the current primary key<br />
   DECLARE cPKColumn CURSOR FOR<br />
      SELECT COLUMN_NAME<br />
      FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE<br />
      WHERE TABLE_NAME = @PkTable AND CONSTRAINT_NAME = @PkName<br />
      ORDER BY ORDINAL_POSITION<br />
   OPEN cPKColumn</p>
<p>   DECLARE @PkColumn SYSNAME<br />
   DECLARE @Order SYSNAME<br />
   DECLARE @Index varchar(max)<br />
   DECLARE @PkFirstColumn BIT SET @PkFirstColumn = 1<br />
   &#8212; Loop through all columns and append the sql statement<br />
   FETCH NEXT FROM cPKColumn INTO @PkColumn<br />
   WHILE (@@FETCH_STATUS = 0)<br />
   BEGIN<br />
      IF (@PkFirstColumn = 1)<br />
         SET @PkFirstColumn = 0<br />
      ELSE<br />
         SET @PKSQL = @PKSQL + &#8216;, &#8216;<br />
	  Select @Order=Case is_descending_key when 0 then &#8216; ASC&#8217; ELSE &#8216; DESC &#8216; END<br />
      from sys.index_columns ic join sys.columns c<br />
      on ic.index_column_id=c.column_id<br />
	  and c.name=@PkColumn<br />
      SET @PKSQL = @PKSQL + @PkColumn + @Order<br />
&#8211;      print charindex(&#8216;ASC,&#8217;,@pksql)<br />
      FETCH NEXT FROM cPKColumn INTO @PkColumn<br />
      END<br />
      Select @Index=&#8217;) WITH &#8216;+&#8217;(PAD_INDEX =&#8217;+CASE is_padded when 0 then &#8216;OFF&#8217; ELSE &#8216;ON&#8217; END+<br />
					&#8221;+&#8217;, STATISTICS_NORECOMPUTE =&#8217;+CASE no_recompute when 0 then &#8216;OFF&#8217; ELSE &#8216;ON&#8217; END+<br />
					&#8221;+&#8217;, SORT_IN_TEMPDB =&#8217;+CASE is_padded when 0 then &#8216;OFF&#8217; ELSE &#8216;ON&#8217; END+<br />
					&#8221;+&#8217;, IGNORE_DUP_KEY =&#8217;+CASE is_padded when 0 then &#8216;OFF&#8217; ELSE &#8216;ON&#8217; END+<br />
					&#8221;+&#8217;, ONLINE =&#8217;+CASE is_padded when 0 then &#8216;OFF&#8217; ELSE &#8216;ON&#8217; END+<br />
					&#8221;+&#8217;, ALLOW_ROW_LOCKS =&#8217;+CASE ALLOW_ROW_LOCKS when 0 then &#8216;OFF&#8217; ELSE &#8216;ON&#8217; END+<br />
					&#8221;+&#8217;, ALLOW_PAGE_LOCKS =&#8217;+CASE ALLOW_PAGE_LOCKS when 0 then &#8216;OFF)&#8217; ELSE &#8216;ON)&#8217; END<br />
					  +&#8217; ON &#8216; +&#8217;['+fg.name+']&#8216;<br />
      from sys.indexes i join sys.stats s<br />
      on i.name=s.name<br />
	  join sys.filegroups fg<br />
      on fg.data_space_id=i.data_space_id<br />
      and i.name=@PkName<br />
      SET @PKSQL = @PKSQL+@index</p>
<p>   CLOSE cPKColumn<br />
   DEALLOCATE cPKColumn</p>
<p>   &#8212; Print the primary key statement<br />
   PRINT @PKSQL</p>
<p>   FETCH NEXT FROM cPK INTO @PkTable, @PkName<br />
END<br />
CLOSE cPK<br />
DEALLOCATE cPK</p>
<p>Pinal, please try the above script for scripting out primary keys at database level and let me know where you think it needs amendment.</p>
<p>Manu</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: pinaldave</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54370</link>
		<dc:creator><![CDATA[pinaldave]]></dc:creator>
		<pubDate>Sun, 02 Aug 2009 13:57:47 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54370</guid>
		<description><![CDATA[Hello All,

I was just going over scripts posted as answer to this question.

So far for Primary Key only one script is close which is of &#039;aasim&#039;.

And for foreign key the script which is close is &#039;Aman&#039;.

There are two things which are missing in aasim&#039;s query
1) FileGrouop which actually the table belongs to as it is hardcoded at this moment.
2) The direction of PK column i.e. ASC or DESC

Let me know if any other expert have other idea.

Kind Regards,
Pinal]]></description>
		<content:encoded><![CDATA[<p>Hello All,</p>
<p>I was just going over scripts posted as answer to this question.</p>
<p>So far for Primary Key only one script is close which is of &#8216;aasim&#8217;.</p>
<p>And for foreign key the script which is close is &#8216;Aman&#8217;.</p>
<p>There are two things which are missing in aasim&#8217;s query<br />
1) FileGrouop which actually the table belongs to as it is hardcoded at this moment.<br />
2) The direction of PK column i.e. ASC or DESC</p>
<p>Let me know if any other expert have other idea.</p>
<p>Kind Regards,<br />
Pinal</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Sandeep</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54340</link>
		<dc:creator><![CDATA[Sandeep]]></dc:creator>
		<pubDate>Fri, 31 Jul 2009 21:00:58 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54340</guid>
		<description><![CDATA[I think best Will be to Use DBPRO ( VSTS Database Edition)to Manage the Database project. DBPRO has a Schema compare feature by which you can get all the primary and foreign key in to the project and deploy it anywhere you wish to.]]></description>
		<content:encoded><![CDATA[<p>I think best Will be to Use DBPRO ( VSTS Database Edition)to Manage the Database project. DBPRO has a Schema compare feature by which you can get all the primary and foreign key in to the project and deploy it anywhere you wish to.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Brian Tkatch</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54319</link>
		<dc:creator><![CDATA[Brian Tkatch]]></dc:creator>
		<pubDate>Fri, 31 Jul 2009 12:25:56 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54319</guid>
		<description><![CDATA[@shekhar sinha

I am having a hard time understanding the TABLE structure. Please post the actual SQL for the TABLE definitions.]]></description>
		<content:encoded><![CDATA[<p>@shekhar sinha</p>
<p>I am having a hard time understanding the TABLE structure. Please post the actual SQL for the TABLE definitions.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: shekhar sinha</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54299</link>
		<dc:creator><![CDATA[shekhar sinha]]></dc:creator>
		<pubDate>Fri, 31 Jul 2009 05:04:30 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54299</guid>
		<description><![CDATA[Dear Sir / Madam,

                           I have a pleasure to mail to you.

 Please go through my concept to give you better ideas and I shall gain

knowledge from you kind people :-

                                Tablename : -------------------------&gt; T1

                                 Rollno_Class-X ---------&gt;PK       


                                 Tablename : -------------------------&gt; T2


                                 Rollno_Class-XII ---------&gt;PK     


                                Tablename : -------------------------&gt; T3


                                 Rollno_Class-Degree ---------&gt;PK

In table------&gt; T1 , T2 and T3 I have only the rollno&#039;s of the candidate. In these table PK&#039;s has been 

defined by not using the syntax of primary key.I have defined it in my way but it follows the rule of

unique and not null both.


                                Tablename : -------------------------&gt; Result_Details1

                                 Rollno_Class-X ---------&gt;FK        


                                Tablename : -------------------------&gt; Result_Details2


                                Rollno_Class-XII ---------&gt;FK     


                                Tablename : -------------------------&gt; Result_Details3

                                Rollno_Class-Degree ---------&gt;FK

Now, my table-----&gt; Result_Details1, Result_Details2, Result_Details3 which is the foreign key of 

above respective PK cols fields have other details also.



                                  Tablename : -------------------------&gt; Records

Rollno_Class-X ---------&gt;PK    Rollno_Class-XII ---------&gt;PK      Rollno_Class-Degree ---------&gt;PK       

PK has been defined as in table-----&gt; T1, T2 and T3.Now, my Table---&gt; Records contains only

Rollno_Class-X ,Rollno_Class-XII and  Rollno_Class-Degree. Which is my PK ? Pls]]></description>
		<content:encoded><![CDATA[<p>Dear Sir / Madam,</p>
<p>                           I have a pleasure to mail to you.</p>
<p> Please go through my concept to give you better ideas and I shall gain</p>
<p>knowledge from you kind people :-</p>
<p>                                Tablename : &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-&gt; T1</p>
<p>                                 Rollno_Class-X &#8212;&#8212;&#8212;&gt;PK       </p>
<p>                                 Tablename : &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-&gt; T2</p>
<p>                                 Rollno_Class-XII &#8212;&#8212;&#8212;&gt;PK     </p>
<p>                                Tablename : &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-&gt; T3</p>
<p>                                 Rollno_Class-Degree &#8212;&#8212;&#8212;&gt;PK</p>
<p>In table&#8212;&#8212;&gt; T1 , T2 and T3 I have only the rollno&#8217;s of the candidate. In these table PK&#8217;s has been </p>
<p>defined by not using the syntax of primary key.I have defined it in my way but it follows the rule of</p>
<p>unique and not null both.</p>
<p>                                Tablename : &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-&gt; Result_Details1</p>
<p>                                 Rollno_Class-X &#8212;&#8212;&#8212;&gt;FK        </p>
<p>                                Tablename : &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-&gt; Result_Details2</p>
<p>                                Rollno_Class-XII &#8212;&#8212;&#8212;&gt;FK     </p>
<p>                                Tablename : &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-&gt; Result_Details3</p>
<p>                                Rollno_Class-Degree &#8212;&#8212;&#8212;&gt;FK</p>
<p>Now, my table&#8212;&#8211;&gt; Result_Details1, Result_Details2, Result_Details3 which is the foreign key of </p>
<p>above respective PK cols fields have other details also.</p>
<p>                                  Tablename : &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-&gt; Records</p>
<p>Rollno_Class-X &#8212;&#8212;&#8212;&gt;PK    Rollno_Class-XII &#8212;&#8212;&#8212;&gt;PK      Rollno_Class-Degree &#8212;&#8212;&#8212;&gt;PK       </p>
<p>PK has been defined as in table&#8212;&#8211;&gt; T1, T2 and T3.Now, my Table&#8212;&gt; Records contains only</p>
<p>Rollno_Class-X ,Rollno_Class-XII and  Rollno_Class-Degree. Which is my PK ? Pls</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: karuta</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54071</link>
		<dc:creator><![CDATA[karuta]]></dc:creator>
		<pubDate>Fri, 24 Jul 2009 13:39:41 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54071</guid>
		<description><![CDATA[The biggest problem is: (SQL1 for copying SQL2) 

If creating the database in SQL2 (with the script generated by the wizard SQL1), including IDENTITY INCREMENT, when you move a database to another, if the fields are not in sequence (1,2,3,4 , 5 ,...) ie the ID&#039;s are out of sequence (eg an ID that was deleted) ... at the time of the copy, you have a logical sequence of numbers ... not following the real ID which is the original base ... I did understand?]]></description>
		<content:encoded><![CDATA[<p>The biggest problem is: (SQL1 for copying SQL2) </p>
<p>If creating the database in SQL2 (with the script generated by the wizard SQL1), including IDENTITY INCREMENT, when you move a database to another, if the fields are not in sequence (1,2,3,4 , 5 ,&#8230;) ie the ID&#8217;s are out of sequence (eg an ID that was deleted) &#8230; at the time of the copy, you have a logical sequence of numbers &#8230; not following the real ID which is the original base &#8230; I did understand?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Gangadhar Naidu</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54065</link>
		<dc:creator><![CDATA[Gangadhar Naidu]]></dc:creator>
		<pubDate>Fri, 24 Jul 2009 13:04:17 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54065</guid>
		<description><![CDATA[Hi All,

When you genarate script through wizard. choose the options Script Indexes also to True. Then choose tables. It will genarate all constraints automatically including IDENTITY INCREMENT.

There is no need to take script especially for primary keys and foreign keys.

Thank you,
Ganga.]]></description>
		<content:encoded><![CDATA[<p>Hi All,</p>
<p>When you genarate script through wizard. choose the options Script Indexes also to True. Then choose tables. It will genarate all constraints automatically including IDENTITY INCREMENT.</p>
<p>There is no need to take script especially for primary keys and foreign keys.</p>
<p>Thank you,<br />
Ganga.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Fenil Desai</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54064</link>
		<dc:creator><![CDATA[Fenil Desai]]></dc:creator>
		<pubDate>Fri, 24 Jul 2009 12:54:25 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54064</guid>
		<description><![CDATA[may be this...

SELECT

TC.CONSTRAINT_NAME AS FOREIGN_KEY_CONSTRAINT_NAME,
TC.TABLE_NAME AS FOREIGN_KEY_TABLE_NAME,
KCU.COLUMN_NAME,
ORDINAL_POSITION AS COLUMN_POSITION,
RC.UNIQUE_CONSTRAINT_NAME AS PARENT_PRIMARY_KEY_NAME,
TC_PK.TABLE_NAME AS PARENT_TABLE_NAME

FROM

INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU,
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC,
INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC_PK

WHERE TC.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME
AND TC.TABLE_NAME = KCU.TABLE_NAME
AND TC.CONSTRAINT_TYPE = &#039;FOREIGN KEY&#039;
AND RC.CONSTRAINT_NAME = TC.CONSTRAINT_NAME
AND RC.UNIQUE_CONSTRAINT_NAME = TC_PK.CONSTRAINT_NAME]]></description>
		<content:encoded><![CDATA[<p>may be this&#8230;</p>
<p>SELECT</p>
<p>TC.CONSTRAINT_NAME AS FOREIGN_KEY_CONSTRAINT_NAME,<br />
TC.TABLE_NAME AS FOREIGN_KEY_TABLE_NAME,<br />
KCU.COLUMN_NAME,<br />
ORDINAL_POSITION AS COLUMN_POSITION,<br />
RC.UNIQUE_CONSTRAINT_NAME AS PARENT_PRIMARY_KEY_NAME,<br />
TC_PK.TABLE_NAME AS PARENT_TABLE_NAME</p>
<p>FROM</p>
<p>INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC,<br />
INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU,<br />
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC,<br />
INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC_PK</p>
<p>WHERE TC.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME<br />
AND TC.TABLE_NAME = KCU.TABLE_NAME<br />
AND TC.CONSTRAINT_TYPE = &#8216;FOREIGN KEY&#8217;<br />
AND RC.CONSTRAINT_NAME = TC.CONSTRAINT_NAME<br />
AND RC.UNIQUE_CONSTRAINT_NAME = TC_PK.CONSTRAINT_NAME</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Fenil Desai</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54063</link>
		<dc:creator><![CDATA[Fenil Desai]]></dc:creator>
		<pubDate>Fri, 24 Jul 2009 12:52:42 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54063</guid>
		<description><![CDATA[How about this..

SELECT TC.CONSTRAINT_NAME,TC.TABLE_NAME ,
KCU.COLUMN_NAME,ORDINAL_POSITION AS COLUMN_POSITION

FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC, INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
WHERE 1=1
AND TC.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME
AND TC.TABLE_NAME = KCU.TABLE_NAME
AND TC.CONSTRAINT_TYPE = &#039;FOREIGN KEY&#039;

dont know if its correct...]]></description>
		<content:encoded><![CDATA[<p>How about this..</p>
<p>SELECT TC.CONSTRAINT_NAME,TC.TABLE_NAME ,<br />
KCU.COLUMN_NAME,ORDINAL_POSITION AS COLUMN_POSITION</p>
<p>FROM<br />
INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC, INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU<br />
WHERE 1=1<br />
AND TC.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME<br />
AND TC.TABLE_NAME = KCU.TABLE_NAME<br />
AND TC.CONSTRAINT_TYPE = &#8216;FOREIGN KEY&#8217;</p>
<p>dont know if its correct&#8230;</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: karuta</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54042</link>
		<dc:creator><![CDATA[karuta]]></dc:creator>
		<pubDate>Fri, 24 Jul 2009 03:35:17 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54042</guid>
		<description><![CDATA[Another big difficulty at the time of copying a database to another location are the fields with “IDENTITY INCREMENT”]]></description>
		<content:encoded><![CDATA[<p>Another big difficulty at the time of copying a database to another location are the fields with “IDENTITY INCREMENT”</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Aman</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54036</link>
		<dc:creator><![CDATA[Aman]]></dc:creator>
		<pubDate>Thu, 23 Jul 2009 22:57:57 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54036</guid>
		<description><![CDATA[I have come up with the following query to generate the script for all the foreign keys in the database:

SELECT &#039;ALTER TABLE dbo.&#039; + T.NAME + &#039; ADD CONSTRAINT &#039; + FK.NAME 

		+ &#039; FOREIGN KEY (&#039; + C.NAME + &#039;) &#039; + &#039; REFERENCES dbo.&#039; 

		+  RT.NAME + &#039;( &#039; + RTC.NAME + &#039;)&#039; 

		+  CASE(FK.delete_referential_action)
			WHEN 0 THEN &#039;ON DELETE NO ACTION&#039;
			WHEN 1 THEN &#039;CASCADE&#039;
		   END	
		+  CASE(FK. update_referential_action)
			WHEN 0 THEN &#039;ON UPDATE NO ACTION&#039;
			WHEN 1 THEN &#039;CASCADE&#039;
		   END	 
FROM SYS.FOREIGN_KEYS FK

INNER JOIN SYS.OBJECTS O ON O.OBJECT_ID = FK.OBJECT_ID

INNER JOIN SYS.FOREIGN_KEY_COLUMNS FKC ON FK.OBJECT_ID = FKC.CONSTRAINT_OBJECT_ID

INNER JOIN SYS.TABLES T ON FK.PARENT_OBJECT_ID = T.OBJECT_ID

INNER JOIN SYS.TABLES RT ON FK.REFERENCED_OBJECT_ID = RT.OBJECT_ID

INNER JOIN SYS.COLUMNS C ON  T.OBJECT_ID = C.OBJECT_ID AND C.COLUMN_ID = FKC.CONSTRAINT_COLUMN_ID 

INNER JOIN SYS.COLUMNS RTC ON  RT.OBJECT_ID = RTC.OBJECT_ID AND RTC.COLUMN_ID = FKC.REFERENCED_COLUMN_ID 

WHERE O.TYPE_DESC = &#039;FOREIGN_KEY_CONSTRAINT&#039;]]></description>
		<content:encoded><![CDATA[<p>I have come up with the following query to generate the script for all the foreign keys in the database:</p>
<p>SELECT &#8216;ALTER TABLE dbo.&#8217; + T.NAME + &#8216; ADD CONSTRAINT &#8216; + FK.NAME </p>
<p>		+ &#8216; FOREIGN KEY (&#8216; + C.NAME + &#8216;) &#8216; + &#8216; REFERENCES dbo.&#8217; </p>
<p>		+  RT.NAME + &#8216;( &#8216; + RTC.NAME + &#8216;)&#8217; </p>
<p>		+  CASE(FK.delete_referential_action)<br />
			WHEN 0 THEN &#8216;ON DELETE NO ACTION&#8217;<br />
			WHEN 1 THEN &#8216;CASCADE&#8217;<br />
		   END<br />
		+  CASE(FK. update_referential_action)<br />
			WHEN 0 THEN &#8216;ON UPDATE NO ACTION&#8217;<br />
			WHEN 1 THEN &#8216;CASCADE&#8217;<br />
		   END<br />
FROM SYS.FOREIGN_KEYS FK</p>
<p>INNER JOIN SYS.OBJECTS O ON O.OBJECT_ID = FK.OBJECT_ID</p>
<p>INNER JOIN SYS.FOREIGN_KEY_COLUMNS FKC ON FK.OBJECT_ID = FKC.CONSTRAINT_OBJECT_ID</p>
<p>INNER JOIN SYS.TABLES T ON FK.PARENT_OBJECT_ID = T.OBJECT_ID</p>
<p>INNER JOIN SYS.TABLES RT ON FK.REFERENCED_OBJECT_ID = RT.OBJECT_ID</p>
<p>INNER JOIN SYS.COLUMNS C ON  T.OBJECT_ID = C.OBJECT_ID AND C.COLUMN_ID = FKC.CONSTRAINT_COLUMN_ID </p>
<p>INNER JOIN SYS.COLUMNS RTC ON  RT.OBJECT_ID = RTC.OBJECT_ID AND RTC.COLUMN_ID = FKC.REFERENCED_COLUMN_ID </p>
<p>WHERE O.TYPE_DESC = &#8216;FOREIGN_KEY_CONSTRAINT&#8217;</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: ashishgilhotra</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54021</link>
		<dc:creator><![CDATA[ashishgilhotra]]></dc:creator>
		<pubDate>Thu, 23 Jul 2009 17:10:58 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54021</guid>
		<description><![CDATA[I think there is one more way by looping all the bases for foreign cases using while loop...
here it is 



create table #Dbs(name varchar(100),isscaned bit)
insert into #Dbs
select name, 0 from sys.databases where database_id &gt; 4 and state = 0;
--select * from #DBS
DECLARE @dbname varchar(100)
DECLARE @SQLSTR varchar(8000)
WHILE (SELECT COUNT(*) FROM #Dbs WHERE isscaned = 0) &gt; 0
    BEGIN
	SELECT TOP 1 @dbname = name
        FROM #Dbs
        WHERE isscaned = 0;

	set @SQLSTR = &#039;USE &#039;+  @dbname;
	exec (@SQLSTR)
		begin

		select &#039;ALTER TABLE &#039;+OBJECT_NAME(f.parent_object_id)+ &#039; ADD CONSTRAINT&#039; + f.name + &#039; FOREIGN KEY&#039;+&#039;(&#039;+COL_NAME(fc.parent_object_id,fc.parent_column_id)+&#039;)&#039;+&#039;REFRENCES &#039;+OBJECT_NAME (f.referenced_object_id)+&#039;(&#039;+COL_NAME(fc.referenced_object_id,fc.referenced_column_id)+&#039;)&#039; as Scripts
		FROM sys.foreign_keys AS f
		INNER JOIN sys.foreign_key_columns AS fc
		ON f.OBJECT_ID = fc.constraint_object_id

		end 

	UPDATE #Dbs
        SET isscaned = 1
        WHERE name = @dbname;
	END]]></description>
		<content:encoded><![CDATA[<p>I think there is one more way by looping all the bases for foreign cases using while loop&#8230;<br />
here it is </p>
<p>create table #Dbs(name varchar(100),isscaned bit)<br />
insert into #Dbs<br />
select name, 0 from sys.databases where database_id &gt; 4 and state = 0;<br />
&#8211;select * from #DBS<br />
DECLARE @dbname varchar(100)<br />
DECLARE @SQLSTR varchar(8000)<br />
WHILE (SELECT COUNT(*) FROM #Dbs WHERE isscaned = 0) &gt; 0<br />
    BEGIN<br />
	SELECT TOP 1 @dbname = name<br />
        FROM #Dbs<br />
        WHERE isscaned = 0;</p>
<p>	set @SQLSTR = &#8216;USE &#8216;+  @dbname;<br />
	exec (@SQLSTR)<br />
		begin</p>
<p>		select &#8216;ALTER TABLE &#8216;+OBJECT_NAME(f.parent_object_id)+ &#8216; ADD CONSTRAINT&#8217; + f.name + &#8216; FOREIGN KEY&#8217;+'(&#8216;+COL_NAME(fc.parent_object_id,fc.parent_column_id)+&#8217;)'+&#8217;REFRENCES &#8216;+OBJECT_NAME (f.referenced_object_id)+&#8217;(&#8216;+COL_NAME(fc.referenced_object_id,fc.referenced_column_id)+&#8217;)&#8217; as Scripts<br />
		FROM sys.foreign_keys AS f<br />
		INNER JOIN sys.foreign_key_columns AS fc<br />
		ON f.OBJECT_ID = fc.constraint_object_id</p>
<p>		end </p>
<p>	UPDATE #Dbs<br />
        SET isscaned = 1<br />
        WHERE name = @dbname;<br />
	END</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Otoniel Diaz</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54020</link>
		<dc:creator><![CDATA[Otoniel Diaz]]></dc:creator>
		<pubDate>Thu, 23 Jul 2009 15:35:29 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54020</guid>
		<description><![CDATA[--Try setting you visual studio as Result to text.
declare @NewLinechar char(2)
set @NewLinechar = char(13) + char(10)  -- This one came from one of your articles
select	&#039;ALTER TABLE [&#039; + s.name + &#039;].[&#039; + t.name + &#039;] ADD CONSTRAINT [&#039; + c.name + &#039;]&#039; + @NewLinechar
			+ &#039;PRIMARY KEY &#039; + i.type_desc collate SQL_Latin1_General_CP1_CI_AS + @NewLinechar
			+ &#039;([&#039; + col.name +&#039;] ASC&#039; + @NewLinechar 
			+ &#039;) on [&#039; + ds.name + &#039;]&#039; + @NewLinechar 
			+&#039;GO&#039;
from	sys.key_constraints c
join	sys.tables t
	on	c.parent_object_id = t.object_Id
join	sys.schemas s
	on	t.schema_id = s.schema_id
join	sys.indexes i
	on	c.unique_index_id = i.index_id
join	sys.index_columns ic
	on	i.object_id = ic.object_id
	and	i.index_id = ic.index_id
join	sys.columns col
	on	t.object_id = col.object_id
	and	ic.column_id = col.column_id
join	sys.data_spaces ds 
	on	i.data_space_id = ds.data_space_id
where	c.type = &#039;PK&#039;]]></description>
		<content:encoded><![CDATA[<p>&#8211;Try setting you visual studio as Result to text.<br />
declare @NewLinechar char(2)<br />
set @NewLinechar = char(13) + char(10)  &#8212; This one came from one of your articles<br />
select	&#8216;ALTER TABLE [' + s.name + '].[' + t.name + '] ADD CONSTRAINT [' + c.name + ']&#8216; + @NewLinechar<br />
			+ &#8216;PRIMARY KEY &#8216; + i.type_desc collate SQL_Latin1_General_CP1_CI_AS + @NewLinechar<br />
			+ &#8216;([' + col.name +'] ASC&#8217; + @NewLinechar<br />
			+ &#8216;) on [' + ds.name + ']&#8216; + @NewLinechar<br />
			+&#8217;GO&#8217;<br />
from	sys.key_constraints c<br />
join	sys.tables t<br />
	on	c.parent_object_id = t.object_Id<br />
join	sys.schemas s<br />
	on	t.schema_id = s.schema_id<br />
join	sys.indexes i<br />
	on	c.unique_index_id = i.index_id<br />
join	sys.index_columns ic<br />
	on	i.object_id = ic.object_id<br />
	and	i.index_id = ic.index_id<br />
join	sys.columns col<br />
	on	t.object_id = col.object_id<br />
	and	ic.column_id = col.column_id<br />
join	sys.data_spaces ds<br />
	on	i.data_space_id = ds.data_space_id<br />
where	c.type = &#8216;PK&#8217;</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: ashishgilhotra</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54019</link>
		<dc:creator><![CDATA[ashishgilhotra]]></dc:creator>
		<pubDate>Thu, 23 Jul 2009 15:17:54 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54019</guid>
		<description><![CDATA[-- Used to generate all foreign keys for each Database
Create table #Scripts(scripts varchar(4000))
insert into #scripts
EXEC sp_MSforeachdb
&#039;USE ?
IF DB_ID(&#039;&#039;?&#039;&#039;) &gt; 4 -- Skip system databases
BEGIN
EXEC (&#039;&#039;
SELECT &#039;&#039;&#039;&#039;ALTER TABLE &#039;&#039;&#039;&#039;+OBJECT_NAME(f.parent_object_id)+
&#039;&#039;&#039;&#039; ADD CONSTRAINT&#039;&#039;&#039;&#039; + f.name + &#039;&#039;&#039;&#039; FOREIGN KEY&#039;&#039;&#039;&#039;+&#039;&#039;&#039;&#039;(&#039;&#039;&#039;&#039;+COL_NAME(fc.parent_object_id,fc.parent_column_id)+&#039;&#039;&#039;&#039;)&#039;&#039;&#039;&#039;
+&#039;&#039;&#039;&#039;REFRENCES &#039;&#039;&#039;&#039;+OBJECT_NAME (f.referenced_object_id)+&#039;&#039;&#039;&#039;(&#039;&#039;&#039;&#039;+COL_NAME(fc.referenced_object_id,
fc.referenced_column_id)+&#039;&#039;&#039;&#039;)&#039;&#039;&#039;&#039; as Scripts
FROM .sys.foreign_keys AS f
INNER JOIN .sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
&#039;&#039;)
END&#039;
select * from #Scripts]]></description>
		<content:encoded><![CDATA[<p>&#8211; Used to generate all foreign keys for each Database<br />
Create table #Scripts(scripts varchar(4000))<br />
insert into #scripts<br />
EXEC sp_MSforeachdb<br />
&#8216;USE ?<br />
IF DB_ID(&#8221;?&#8221;) &gt; 4 &#8212; Skip system databases<br />
BEGIN<br />
EXEC (&#8221;<br />
SELECT &#8221;&#8221;ALTER TABLE &#8221;&#8221;+OBJECT_NAME(f.parent_object_id)+<br />
&#8221;&#8221; ADD CONSTRAINT&#8221;&#8221; + f.name + &#8221;&#8221; FOREIGN KEY&#8221;&#8221;+&#8221;&#8221;(&#8221;&#8221;+COL_NAME(fc.parent_object_id,fc.parent_column_id)+&#8221;&#8221;)&#8221;&#8221;<br />
+&#8221;&#8221;REFRENCES &#8221;&#8221;+OBJECT_NAME (f.referenced_object_id)+&#8221;&#8221;(&#8221;&#8221;+COL_NAME(fc.referenced_object_id,<br />
fc.referenced_column_id)+&#8221;&#8221;)&#8221;&#8221; as Scripts<br />
FROM .sys.foreign_keys AS f<br />
INNER JOIN .sys.foreign_key_columns AS fc<br />
ON f.OBJECT_ID = fc.constraint_object_id<br />
&#8221;)<br />
END&#8217;<br />
select * from #Scripts</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: aasim</title>
		<link>http://blog.sqlauthority.com/2009/07/23/sql-server-puzzle-write-script-to-generate-primary-key-and-foreign-key/#comment-54005</link>
		<dc:creator><![CDATA[aasim]]></dc:creator>
		<pubDate>Thu, 23 Jul 2009 09:49:41 +0000</pubDate>
		<guid isPermaLink="false">http://blog.sqlauthority.com/?p=6032#comment-54005</guid>
		<description><![CDATA[-- Get all existing primary keys
DECLARE cPK CURSOR FOR

  SELECT DISTINCT C.TABLE_NAME, C.CONSTRAINT_NAME , F.NAME  
   FROM  SYS.INDEXES I
		INNER JOIN SYS.FILEGROUPS F
			ON I.DATA_SPACE_ID = F.DATA_SPACE_ID
		INNER JOIN SYS.ALL_OBJECTS O
			ON I.[OBJECT_ID] = O.[OBJECT_ID]
		INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
			ON O.NAME = C.TABLE_NAME
	WHERE C.CONSTRAINT_TYPE = &#039;PRIMARY KEY&#039;
	ORDER BY C.TABLE_NAME


DECLARE @PkTable SYSNAME
DECLARE @PkName SYSNAME
DECLARE @FileName SYSNAME

-- Loop through all the primary keys
OPEN cPK
FETCH NEXT FROM cPK INTO @PkTable, @PkName , @FileName
WHILE (@@FETCH_STATUS = 0)
BEGIN
   DECLARE @PKSQL NVARCHAR(4000) SET @PKSQL = &#039;&#039;
   SET @PKSQL = &#039;ALTER TABLE &#039; + @PkTable + &#039; ADD CONSTRAINT &#039; + @PkName + &#039; PRIMARY KEY CLUSTERED (&#039;

   -- Get all columns for the current primary key
   DECLARE cPKColumn CURSOR FOR
      SELECT COLUMN_NAME 
      FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
      WHERE TABLE_NAME = @PkTable AND CONSTRAINT_NAME = @PkName
      ORDER BY ORDINAL_POSITION
   OPEN cPKColumn

   DECLARE @PkColumn SYSNAME
   DECLARE @PkFirstColumn BIT SET @PkFirstColumn = 1
   -- Loop through all columns and append the sql statement
   FETCH NEXT FROM cPKColumn INTO @PkColumn
   WHILE (@@FETCH_STATUS = 0)
   BEGIN
      IF (@PkFirstColumn = 1)
         SET @PkFirstColumn = 0
      ELSE
         SET @PKSQL = @PKSQL + &#039;, &#039;

      SET @PKSQL = @PKSQL + @PkColumn 

      FETCH NEXT FROM cPKColumn INTO @PkColumn
   END
   CLOSE cPKColumn
   DEALLOCATE cPKColumn

   SET @PKSQL = @PKSQL + &#039;)&#039; + &#039; ON &#039;+@FileName
   -- Print the primary key statement
   PRINT @PKSQL

   FETCH NEXT FROM cPK INTO @PkTable, @PkName, @FileName
END
CLOSE cPK
DEALLOCATE cPK]]></description>
		<content:encoded><![CDATA[<p>&#8211; Get all existing primary keys<br />
DECLARE cPK CURSOR FOR</p>
<p>  SELECT DISTINCT C.TABLE_NAME, C.CONSTRAINT_NAME , F.NAME<br />
   FROM  SYS.INDEXES I<br />
		INNER JOIN SYS.FILEGROUPS F<br />
			ON I.DATA_SPACE_ID = F.DATA_SPACE_ID<br />
		INNER JOIN SYS.ALL_OBJECTS O<br />
			ON I.[OBJECT_ID] = O.[OBJECT_ID]<br />
		INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C<br />
			ON O.NAME = C.TABLE_NAME<br />
	WHERE C.CONSTRAINT_TYPE = &#8216;PRIMARY KEY&#8217;<br />
	ORDER BY C.TABLE_NAME</p>
<p>DECLARE @PkTable SYSNAME<br />
DECLARE @PkName SYSNAME<br />
DECLARE @FileName SYSNAME</p>
<p>&#8211; Loop through all the primary keys<br />
OPEN cPK<br />
FETCH NEXT FROM cPK INTO @PkTable, @PkName , @FileName<br />
WHILE (@@FETCH_STATUS = 0)<br />
BEGIN<br />
   DECLARE @PKSQL NVARCHAR(4000) SET @PKSQL = &#8221;<br />
   SET @PKSQL = &#8216;ALTER TABLE &#8216; + @PkTable + &#8216; ADD CONSTRAINT &#8216; + @PkName + &#8216; PRIMARY KEY CLUSTERED (&#8216;</p>
<p>   &#8212; Get all columns for the current primary key<br />
   DECLARE cPKColumn CURSOR FOR<br />
      SELECT COLUMN_NAME<br />
      FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE<br />
      WHERE TABLE_NAME = @PkTable AND CONSTRAINT_NAME = @PkName<br />
      ORDER BY ORDINAL_POSITION<br />
   OPEN cPKColumn</p>
<p>   DECLARE @PkColumn SYSNAME<br />
   DECLARE @PkFirstColumn BIT SET @PkFirstColumn = 1<br />
   &#8212; Loop through all columns and append the sql statement<br />
   FETCH NEXT FROM cPKColumn INTO @PkColumn<br />
   WHILE (@@FETCH_STATUS = 0)<br />
   BEGIN<br />
      IF (@PkFirstColumn = 1)<br />
         SET @PkFirstColumn = 0<br />
      ELSE<br />
         SET @PKSQL = @PKSQL + &#8216;, &#8216;</p>
<p>      SET @PKSQL = @PKSQL + @PkColumn </p>
<p>      FETCH NEXT FROM cPKColumn INTO @PkColumn<br />
   END<br />
   CLOSE cPKColumn<br />
   DEALLOCATE cPKColumn</p>
<p>   SET @PKSQL = @PKSQL + &#8216;)&#8217; + &#8216; ON &#8216;+@FileName<br />
   &#8212; Print the primary key statement<br />
   PRINT @PKSQL</p>
<p>   FETCH NEXT FROM cPK INTO @PkTable, @PkName, @FileName<br />
END<br />
CLOSE cPK<br />
DEALLOCATE cPK</p>
]]></content:encoded>
	</item>
</channel>
</rss>

