<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>foreign-key &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/foreign-key/</link>
	<description>Feed of posts on WordPress.com tagged "foreign-key"</description>
	<pubDate>Mon, 07 Dec 2009 15:04:53 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[mysql - add a foreign key]]></title>
<link>http://deanch.wordpress.com/2009/11/27/mysql-add-a-foreign-key/</link>
<pubDate>Fri, 27 Nov 2009 05:27:53 +0000</pubDate>
<dc:creator>deanch</dc:creator>
<guid>http://deanch.wordpress.com/2009/11/27/mysql-add-a-foreign-key/</guid>
<description><![CDATA[How to add a foreign key to a mysql table: alter table line_items add FOREIGN KEY fk_line_item_order]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>How to add a foreign key to a mysql table:</p>
<pre class="brush: sql;">
alter table line_items add FOREIGN KEY fk_line_item_orders (product_id) references orders(id);
</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Basic Hibernate @OneToOne @PrimaryKeyJoinColumn Example With Maven and MySQL]]></title>
<link>http://devblog.point2.com/2009/11/14/basic-hibernate-onetoone-primarykeyjoincolumn-example-with-maven-and-mysql/</link>
<pubDate>Sat, 14 Nov 2009 15:33:04 +0000</pubDate>
<dc:creator>Damien Gabrielson</dc:creator>
<guid>http://devblog.point2.com/2009/11/14/basic-hibernate-onetoone-primarykeyjoincolumn-example-with-maven-and-mysql/</guid>
<description><![CDATA[Recently we had a story which involved improving one of our data models. The table for the model had]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Recently we had a <a href="http://www.agilemodeling.com/artifacts/userStory.htm">story</a> which involved improving one of our data models. The table for the model had grown quite wide and we wanted to improve normalization and performance. We wanted to move a few columns from our original table (Listing) to a new table with the primary key of the new table (ListingLocation) also being a foreign key to the primary key of the original table, our <a href="http://www.xylax.net/hibernate/onetoone.html">one-to-one relationship</a>. I will try to detail how we accomplished this change using a simplified example. Source code is linked at the bottom of this post.</p>
<p>Here is the entity relationship diagram of the old, single table structure:<br />
<img class="alignnone size-full wp-image-1080" title="ERD-old" src="http://point2blog.wordpress.com/files/2009/11/erd-old.png" alt="Old ER Diagram" width="175" height="98" /><br />
And here is the entity relationship diagram of the new, two table structure:<br />
<img class="alignnone size-full wp-image-1081" title="ERD-new" src="http://point2blog.wordpress.com/files/2009/11/erd-new.png" alt="New ER Diagram" width="377" height="82" /></p>
<p>As you can see, it is a very simple example of a very common relationship in the database. However, what we found when implementing this in <a href="https://www.hibernate.org/">Hibernate</a> was not a simple as I had hoped.</p>
<p>To get started here is the SQL used to represent our new tables:<br />
<code><br />
CREATE TABLE Listing<br />
(<br />
id BIGINT(20) NOT NULL AUTO_INCREMENT,<br />
price DECIMAL(10,2),<br />
PRIMARY KEY (id)<br />
) TYPE = INNODB;</code><br />
<code><br />
CREATE TABLE ListingLocation<br />
(<br />
listingID BIGINT(20) NOT NULL,<br />
address VARCHAR(255),<br />
PRIMARY KEY(listingID),<br />
INDEX (listingID),<br />
FOREIGN KEY (listingID) REFERENCES Listing (id)<br />
) TYPE = INNODB;<br />
</code></p>
<p>I&#8217;ve used MySQL for this example because it is free and easy to setup. InnoDB table types have been because they allow <a href="http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html">foreign keys</a>, which is crucial to this example.</p>
<p>Our old Listing entity was pretty basic; it looked something like this (imports &#38; getters/setters excluded):<br />
<code><br />
@Entity<br />
@Table<br />
public class Listing implements Serializable {<br />
@Id<br />
@GeneratedValue<br />
private long id;<br />
@Column(columnDefinition= "DECIMAL(10,2)")<br />
private double price;<br />
private String address;<br />
...<br />
</code><br />
In this case, creating a new instance of Listing and persisting it is very easy. When we split the entities, it becomes a little more complicated. Here is what our entities looked like after being split:<br />
<code><br />
@Entity<br />
@Table<br />
public class Listing implements Serializable {<br />
@Id<br />
@GeneratedValue<br />
private long id;<br />
@Column(columnDefinition= "DECIMAL(10,2)")<br />
private double price;<br />
@OneToOne<br />
@PrimaryKeyJoinColumn<br />
private ListingLocation listingLocation;<br />
...<br />
</code><br />
and<br />
<code><br />
@Entity<br />
@Table<br />
public class ListingLocation implements Serializable {<br />
@Id<br />
@Column(name = "listingID")<br />
private Long id;<br />
private String address;<br />
...<br />
</code></p>
<p>The differences are not large, but there are a couple important points to note:</p>
<ul>
<li>Adding ListingLocation to Listing with @OneToOne &#38; @PrimaryKeyJoinColumn annotations tells Hibernate the Listing has a one-to-one mapping with ListingLocation by using the Primary Key as the join column.</li>
<li>Adding @Id &#38; @Column(name = &#8220;listingID&#8221;) annotations to our id field in ListingLocation tells Hibernate that id is, well, an ID, but that column should not be called &#8220;id&#8221; in the DB, but &#8220;listingID&#8221; as that will help an observer see the relationship quickly without looking closely at the schema. Also, it is good to note that the @GeneratedValue is not on &#8220;id&#8221; in ListingLocation as it is in Listing as we want to specify exactly what goes in that field.</li>
</ul>
<p>The biggest gripe I have with using the one-to-one relationship is that we can no longer save Listing only. Our REAL Listing entity is far more complex with several relationships, but this was the first one-to-one relationship with Hibernate. Previously we could do something like:<br />
<code><br />
Listing listing = new Listing();<br />
listing.setPrice(price);<br />
listing.setAddress(address);<br />
listing.setFoo(foo); // where foo is a @OneToMany annotated entity<br />
...<br />
<strong>session.save(listing);</strong><br />
</code><br />
Now, we must save Listing and ListingLocation separately like this:<br />
<code><br />
ListingLocation listingLocation = new ListingLocation();<br />
listingLocation.setAddress(address);<br />
Listing listing = new Listing();<br />
listing.setPrice(price);<br />
listing.setListingLocation(listingLocation);<br />
...<br />
<strong>session.save(listing);</strong><br />
if (listing.getListingLocation() != null) {<br />
listing.getListingLocation().setId(listing.getId());<br />
<strong>session.save(listing.getListingLocation()); // save ListingLocation</strong><br />
}<br />
</code></p>
<p>I guess I&#8217;m just a bit spoiled, but I was hoping that this would bit more automatic, as it is with the one-to-many/many-to-one relationships.</p>
<p style="text-align:left;">I have written a small app that uses these two entities and inserts a row into each table, the link is available at the bottom of this post. The config (hibernate.cfg.xml) expects that you have MySQL running on 127.0.0.1 with a DB named &#8216;OneToOneDemo&#8217; with a user named &#8216;root&#8217; and a password of &#8216;password&#8217;; I have included the SQL (Setup-OneToOneDemo.sql) to setup the DB. Just extract the contents of the archive, navigate to the project directory, and from the command line/terminal run:<br />
<code><br />
mvn clean compile exec:java -Dexec.mainClass=com.point2.onetoonedemo.App -e<br />
</code></p>
<p>You should see the following output:<br />
<code><br />
@OneToOne @PrimaryKeyJoinColumn Hibernate Demo<br />
----------------------------------------------<br />
...<br />
Hibernate:<br />
insert into Listing (price) values (?)</code></p>
<p><code>Hibernate:<br />
insert into ListingLocation (address, listingID) values (?, ?)<br />
Saved listing ID: 1<br />
</code></p>
<p><a href="http://sites.google.com/site/gabrielsond/home/OneToOneDemo.zip?attredirects=0&#38;d=1">Download Source Code</a> (12 KB .ZIP)</p>
<p>If you have any questions, comments, or suggestions on how to do better accomplish one-to-one Hibernate mappings, I would love to hear about them. If you have any problems getting the code to compile and/or run, please let me know and I will make the necessary changes. Everything should just work, providing you modify the hibernate config or setup your DB. I had a difficult time finding complete and recent documentation on this subject so I hope this post and the maven project will help.</p>
<p>By: <a href="http://devblog.point2.com/author/dgp2/" target="_blank">Damien Gabrielson</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[T-SQL Foreign Key (FK) Index Creator]]></title>
<link>http://blogbustingbeats.wordpress.com/2009/09/25/t-sql-foreign-key-fk-index-creator-non-unique-and-non-clustered-2/</link>
<pubDate>Fri, 25 Sep 2009 12:59:25 +0000</pubDate>
<dc:creator>blogbustingbeats</dc:creator>
<guid>http://blogbustingbeats.wordpress.com/2009/09/25/t-sql-foreign-key-fk-index-creator-non-unique-and-non-clustered-2/</guid>
<description><![CDATA[/* FOREIGN KEY INDEX CREATOR THIS SCRIPT GENERATES SQL TO DROPS AND RECREATE NON-CLUSTERED INDEXES O]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><code><br />
/*<br />
FOREIGN KEY INDEX CREATOR</p>
<p>THIS SCRIPT GENERATES SQL TO DROPS AND RECREATE NON-CLUSTERED INDEXES ON ALL FK COLUMNS<br />
SET @FK_PREFIX TO MATCH THE FOREIGN KEY PREFIX IN YOUR DATABASE.</p>
<p>SQL2005 AND ABOVE ONLY (SYS VIEWS)<br />
*/</p>
<p>DECLARE @FK_PREFIX NVARCHAR(50)<br />
SET @FK_PREFIX = 'FK_'</p>
<p>DECLARE @CONSTRAINT_NAME NVARCHAR(255)<br />
DECLARE @TABLE_SCHEMA NVARCHAR(255)<br />
DECLARE @TABLE_NAME NVARCHAR(255)<br />
DECLARE @COLUMN_NAME NVARCHAR(255)</p>
<p>DECLARE FK_INDEX_CURSOR CURSOR READ_ONLY<br />
FOR SELECT<br />
            CONSTRAINT_NAME, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME<br />
      FROM<br />
            INFORMATION_SCHEMA.KEY_COLUMN_USAGE</p>
<p>OPEN FK_INDEX_CURSOR<br />
FETCH NEXT FROM FK_INDEX_CURSOR INTO @CONSTRAINT_NAME, @TABLE_SCHEMA, @TABLE_NAME, @COLUMN_NAME<br />
WHILE (@@fetch_status  -1)<br />
BEGIN<br />
      IF (@@fetch_status  -2)<br />
            BEGIN</p>
<p>            IF CHARINDEX(@FK_PREFIX, @CONSTRAINT_NAME) = 1 BEGIN<br />
                  PRINT '     </p>
<p>/****** Object:  Index [IX_' + @CONSTRAINT_NAME + ']    Script Date: ' + CONVERT(NVARCHAR(50), GetDate()) + ' ******/<br />
      IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N''[' + @TABLE_SCHEMA + '].[' + @TABLE_NAME + ']'') AND name = N''IX_' + @CONSTRAINT_NAME + ''')<br />
            DROP INDEX [IX_' + @CONSTRAINT_NAME + '] ON [' + @TABLE_SCHEMA + '].[' + @TABLE_NAME + '] WITH ( ONLINE = OFF )<br />
      GO</p>
<p>      CREATE NONCLUSTERED INDEX [IX_' + @CONSTRAINT_NAME + '] ON [' + @TABLE_SCHEMA + '].[' + @TABLE_NAME + ']<br />
      (<br />
            [' + @COLUMN_NAME + '] ASC<br />
      )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)<br />
      ON [PRIMARY]<br />
      GO</p>
<p>                  '</p>
<p>            END<br />
      END<br />
    FETCH NEXT FROM FK_INDEX_CURSOR INTO @CONSTRAINT_NAME, @TABLE_SCHEMA, @TABLE_NAME, @COLUMN_NAME<br />
END</p>
<p>CLOSE FK_INDEX_CURSOR<br />
DEALLOCATE FK_INDEX_CURSOR</p>
<p></code></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Define Pramary,Foreign,Composite, Candidate and Alternate keys]]></title>
<link>http://mycodelines.wordpress.com/2009/08/26/define-pramaryforeigncomposite-candidate-and-alternate-keys/</link>
<pubDate>Wed, 26 Aug 2009 09:47:26 +0000</pubDate>
<dc:creator>Lakshmi Sravanthi Chowdam</dc:creator>
<guid>http://mycodelines.wordpress.com/2009/08/26/define-pramaryforeigncomposite-candidate-and-alternate-keys/</guid>
<description><![CDATA[Primary key:-  The attribute or combination of attributes that uniquely identifies a row or record. ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><code><strong>Primary key:-  </strong>The attribute or combination of attributes </code><code>that uniquely identifies a row or record.</code></p>
<p><code><strong>Foreign Key:-</strong> an attribute or combination of attribute in a </code><code>table whose value match a primary key in another table.</code></p>
<p><code><strong>Composite key:-</strong> A primary key that consistsof two or more </code><code>attributes is known as composite key.</code></p>
<p><code><strong>Candidate key:-</strong>  is a column in a table which has the </code><code>ability to become a primary key.</code></p>
<p><code><strong>Alternate Key:-</strong> Any of the candidate keys that is not part </code><code>of the primary key is called an alternate key.</code></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Check Tables and Value Tables in SAP]]></title>
<link>http://naveenvishal.wordpress.com/2009/08/11/check-tables-and-value-tables-in-sap/</link>
<pubDate>Tue, 11 Aug 2009 06:28:55 +0000</pubDate>
<dc:creator>naveenvishal</dc:creator>
<guid>http://naveenvishal.wordpress.com/2009/08/11/check-tables-and-value-tables-in-sap/</guid>
<description><![CDATA[Many ABAPers gets confused initially with these tables. The difference lies in there Implementation ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="text-align:justify;">Many ABAPers gets confused initially with these tables. The difference lies in there Implementation and Behavior. Lets have a closer look at each to understand them better.</p>
<p style="text-align:justify;"> </p>
<p style="text-align:justify;"><!--more--></p>
<p style="text-align:justify;"><strong><span style="color:#339966;">Value Table</span></strong></p>
<p style="text-align:justify;"> This is maintained at Domain Level.</p>
<div class="mceTemp mceIEcenter" style="text-align:justify;">
<dl class="wp-caption aligncenter">
<dt class="wp-caption-dt"><img class="size-full wp-image-689" title="Defining Value Table" src="http://naveenvishal.wordpress.com/files/2009/08/value_table.jpg" alt="Defining Value Table" width="450" height="326" /></dt>
<dd class="wp-caption-dd">Defining Value Table</dd>
</dl>
</div>
<p style="text-align:justify;">In some cases you already know when you define a domain that all the fields referring to this domain should be checked against a certain table. This information can be stored in the domain by entering a value table.</p>
<p style="text-align:justify;"> The system proposes the value table as check table when you try to define a foreign key for this field. You can override this proposal.</p>
<p style="text-align:justify;"> Entering a value table does not implement a check. The check against the value table only takes place when a foreign key is defined.</p>
<p style="text-align:justify;"> </p>
<p style="text-align:justify;"> <strong><span style="color:#339966;">Check table</span></strong></p>
<p style="text-align:justify;"> Table whose key fields are used to check the foreign key fields (see Foreign Keys). Only entries that are contained in the key fields of the check table can be contained in the foreign key fields. </p>
<div id="attachment_690" class="wp-caption aligncenter" style="width: 460px"><img class="size-full wp-image-690" title="Defining Check Table" src="http://naveenvishal.wordpress.com/files/2009/08/value_table1.jpg" alt="Defining Check Table" width="450" height="324" /><p class="wp-caption-text">Defining Check Table</p></div>
<p>The check table is used to check whether the input values are valid and for the input help (F4 help).</p>
<p style="text-align:justify;">For example you have Employee master table &#38; Employee Transaction table.</p>
<p style="text-align:justify;">When ever an employee Transacts we need to check whether that employee exists , so we can refer to the employee master table. This is nothing but a Parent &#38; Child relationship . Here data can be maintained at client level, no development involved.</p>
<p style="text-align:justify;"> As per DBMS what we call Parent table, is called as check table in SAP.</p>
<p style="text-align:justify;"> </p>
<p style="text-align:justify;"><strong><span style="color:#339966;">Notable Difference</span></strong></p>
<p style="text-align:justify;">The contents of the check will be used as an input help(F4 Help) for a particular field on which a check table is assigned. But the contents of Value Table are never used in Input Help.</p>
<p style="text-align:justify;"> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to access foreign key values?]]></title>
<link>http://weboom.wordpress.com/2009/08/02/how-to-access-foreign-key-values/</link>
<pubDate>Sun, 02 Aug 2009 06:11:08 +0000</pubDate>
<dc:creator>weboom</dc:creator>
<guid>http://weboom.wordpress.com/2009/08/02/how-to-access-foreign-key-values/</guid>
<description><![CDATA[Foreign key is set in one-to-many relation. For example, Publisher &#8211; Book &#8212;- class Book(]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Foreign key is set in one-to-many relation.</p>
<p>For example,</p>
<p>Publisher &#8211; Book</p>
<p>&#8212;-</p>
<p>class Book(models.Model):</p>
<p>publisher = models.ForeignKey(Publisher)</p>
<p>&#8212;&#8211;</p>
<p>There are two cases:</p>
<p>&#62;&#62;&#62; b = Book.objects.get(id=78)</p>
<p>&#62;&#62;&#62;b.publisher</p>
<p>&#62;&#62;&#62;p=Publisher.objects.get(name=&#8217;Aplus&#8217;)</p>
<p>&#62;&#62;&#62;p.book_set.all()</p>
<p>Note that book_set</p>
<p>is just a QuerySet.</p>
<p>Thus it can be filtered and sliced.</p>
<p>&#62;&#62;&#62;p.book_set.filter(name__icontains=&#8217;django&#8217;).order_by(&#8216;name&#8217;)[0:2]</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[외래키(Foreign key) 설정옵션]]></title>
<link>http://spaceufo.wordpress.com/2009/06/16/%ec%99%b8%eb%9e%98%ed%82%a4foreign-key-%ec%84%a4%ec%a0%95%ec%98%b5%ec%85%98/</link>
<pubDate>Tue, 16 Jun 2009 19:44:33 +0000</pubDate>
<dc:creator>spaceufo</dc:creator>
<guid>http://spaceufo.wordpress.com/2009/06/16/%ec%99%b8%eb%9e%98%ed%82%a4foreign-key-%ec%84%a4%ec%a0%95%ec%98%b5%ec%85%98/</guid>
<description><![CDATA[Table 작성/수정 시 적용할 수 있는 외래키(Foreign key)의 설정옵션 : 외래키(Foreign key) 조건을 만족시키기 위하여 부모테이블/자식 테이블에 어떤 행위가 ]]></description>
<content:encoded><![CDATA[Table 작성/수정 시 적용할 수 있는 외래키(Foreign key)의 설정옵션 : 외래키(Foreign key) 조건을 만족시키기 위하여 부모테이블/자식 테이블에 어떤 행위가 ]]></content:encoded>
</item>
<item>
<title><![CDATA[Deadlock Investigation Example]]></title>
<link>http://hpdba.wordpress.com/2009/06/16/deadlock-investigation-example/</link>
<pubDate>Mon, 15 Jun 2009 15:08:39 +0000</pubDate>
<dc:creator>hpdba</dc:creator>
<guid>http://hpdba.wordpress.com/2009/06/16/deadlock-investigation-example/</guid>
<description><![CDATA[DBINST started to display the following error message: ORA-00060: Deadlock detected. More info in fi]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>DBINST started to display the following error message:</p>
<pre>ORA-00060: Deadlock detected. More info in file /u01/app/oracle/admin/DBINST/udump/DBINST_ora_1705.trc.</pre>
<p>When the deadlocks occurred, the application was failing and logging errors too.</p>
<p>Oracle Concept Manual: &#8220;<em>A deadlock can occur when two or more users are waiting for data locked by each other. Deadlocks prevent some transactions from continuing to work. &#8230; Oracle automatically detects deadlock situations and resolves them by rolling back one of the statements involved in the deadlock, thereby releasing one set of the conflicting row locks.</em> &#8220;</p>
<p>The start of the trace files were similar to each other, so it appeared to be the same piece of code causing the problem:</p>
<pre>DEADLOCK DETECTED
Current SQL statement for this session:
delete from PORTDETAIL where ID=:1 and version=:2
The following deadlock is not an ORACLE error. It is a
deadlock due to user error in the design of an application
or from issuing incorrect ad-hoc SQL. The following
information may aid in determining the deadlock:
Deadlock graph:
---------Blocker(s)--------  ---------Waiter(s)---------
Resource Name          process session holds waits  process session holds waits
<span style="color:#00ff00;">TM</span>-<span style="color:#00ff00;">0000e7bc</span>-00000000        28     132    SX   SSX       25     135    SX   SSX
<span style="color:#00ff00;">TM</span>-<span style="color:#00ff00;">0000e7bc</span>-00000000        25     135    SX   SSX       28     132    SX   SSX
session 132: DID 0001-001C-0000052F     session 135: DID 0001-0019-00000B29
session 135: DID 0001-0019-00000B29     session 132: DID 0001-001C-0000052F
<span style="color:#ff0000;">Rows waited on</span>:
Session 135: obj - rowid = 0000E7DC - AAAOfcAAFAAAAjIAAA
(dictionary objn - 59356, file - 5, block - 2248, slot - 0)
Session 132: obj - rowid = 0000E7DC - AAAOfcAAFAAAAjIAAA
(dictionary objn - 59356, file - 5, block - 2248, slot - 0)
Information on the OTHER waiting sessions:
Session 135:
pid=25 serial=1301 audsid=134658 user: 60/EGSCHEMA
O/S info: user: , term: , ospid: 1234, machine: dbserver.local
program:
Current SQL Statement:
delete from PORTDETAIL where ID=:1 and version=:2
End of information on OTHER waiting sessions.</pre>
<p>I looked noticed that this was a bit different than other deadlocks I&#8217;ve seen; it was dead locking on <span style="color:#00ff00;">table locks</span> instead of row locks (transactions).  This made me suspect a foreign key wasn&#8217;t indexed.  (It could be the result of an application doing something unusual, like issuing lock table commands or DDL even).</p>
<p>So in this case we should ignore the &#8220;<span style="color:#ff0000;">Rows waited on</span>&#8221; section, which is useful when we have blocking transactions (TX).</p>
<p>I checked which table was locked:</p>
<p>TM=table lock (DML lock)<br />
<span style="color:#00ff00;">0&#215;0000e7bc</span>=59324</p>
<pre>select owner, object_name from dba_objects where DATA_OBJECT_ID=59324;
OWNER
------------------------------
OBJECT_NAME
------------------------------
EGSCHEMA
PORTSERVICEORDER</pre>
<p>Note that this isn&#8217;t the table in the SQL statement for either session: PORTDETAIL.</p>
<p>So, is there a trigger or a foreign key that could cause a lock on PORTSERVICEORDER when a row from PORTDETAIL is deleted?</p>
<pre>@dd
EGSCHEMA
PORTDETAIL
TYPE              NAME                           OWNER                          'SOF 'REFERENCED'  NULL
----------------- ------------------------------ ------------------------------ ---- ------------- ------------------------------
INDEX             PD_PSO_IDX                     EGSCHEMA                       HARD ON_OBJECT
INDEX             PK_PORTDETAIL                  EGSCHEMA                       HARD ON_OBJECT
TABLE             PORTITEM                       EGSCHEMA                       HARD FK_REF_OBJECT FK_PORTITEM_PORTDETAIL
TABLE             PORTSERVICEORDER               EGSCHEMA                       HARD FK_REF_OBJECT FK_PSO_APPROVEDPORTDETAILS
TABLE             PORTSERVICEORDER               EGSCHEMA                       HARD FK_REF_OBJECT FK_PSO_GSPPORTDETAILS
VIEW              VIEW_GC_LC_FOR_COMPLETED_PORTS EGSCHEMA                       SOFT REFERENCED</pre>
<p>Yes!  Two foreign keys.</p>
<p>Are these foreign keys indexed?</p>
<pre>@$DBA_SQLPATH/apt/missing_fk_indexes.sql
TABLE_NAME                                       COLUMN_NAME
------------------------------------------------ ------------------------------
EGSCHEMA.PORTSERVICEORDER                        APPROVEDPORTDETAILS
EGSCHEMA.PORTSERVICEORDER                        GSPPORTDETAILS</pre>
<p>No, neither of them are indexed.</p>
<h2>My Interpretation</h2>
<p>A row is being updated or deleted from the child PORTSERVICEORDER, and then a row is deleted from the parent table PORTDETAIL in the same transaction.  There is no index on the foreign key so a lock is taken on the whole PORTSERVICEORDER table.  When two sessions attempt these same steps concurrently, they would deadlock because they both hold an SX (row exclusive) lock in PORTSERVICEORDER and both are asking for an SSX (share sub-exclusive) lock on PORTSERVICEORDER.</p>
<p>In general, foreign keys should be indexed unless the parent table has very little DML on it.  So&#8230; I asked the developers to index these foreign keys and we haven&#8217;t had deadlocks since.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Primary, Foreign, Alternate Key (Oracle)]]></title>
<link>http://oracle1st.wordpress.com/2009/06/13/primary-foreign-alternate-key-oracle/</link>
<pubDate>Sat, 13 Jun 2009 15:09:09 +0000</pubDate>
<dc:creator>oracle1st</dc:creator>
<guid>http://oracle1st.wordpress.com/2009/06/13/primary-foreign-alternate-key-oracle/</guid>
<description><![CDATA[Key dalam Bahasa Indonesia berarti kunci, maka semakna dengan itu fungsi dari key-key yang berada pa]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Key dalam Bahasa Indonesia berarti kunci, maka semakna dengan itu fungsi dari key-key yang berada pada sebuah database. Artinya setiap pintu pasti mempunyai kunci khusus untuk membukanya, begitu pula tabel dalam database. Key-key inilah yang membantu dalam pengolahan data pada sebuah tabel (<em>insert, update, delete</em>).</p>
<p><!--more--></p>
<p>Secara global key-key dalam Oracle dapat dibagi sebagai berikut :</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td valign="top">Primary Key</td>
<td style="padding-left:10px;" valign="top">:</td>
<td style="padding-left:10px;" valign="top">Key yang mengindentifikasikan bahwa setiap record pasti <em>unique</em>. Dalam sebuah tabel hanya diperbolehkan <strong>satu</strong> primary key, tidak lebih. Misalnya adalah tabel MURID, tidak ada murid yang memiliki NIS (Nomor Induk Siswa) yang sama dalam keadaan real, kemudian diimplementasikan dalam bentuk tabel dengan diberikan <em><strong>primary key</strong></em> pada kolom NIS.</td>
</tr>
<tr>
<td valign="top">Foreign Key</td>
<td style="padding-left:10px;" valign="top">:</td>
<td style="padding-left:10px;" valign="top">Key yang dihasilkan dari <em><strong>primary key</strong></em> dari tabel lain sebagai bentuk referensi dari tabel lain tersebut. Misalnya adalah tabel BELAJAR, dalam proses pembelajaran dibutuhkan kelas, guru dan apa yang dipelajari alias mata pelajaran, maka diimplementasikan dalam sebuah tabel bahwa dalam tabel BELAJAR terdapat <em><strong>foreign key</strong></em> (key asing) dari tabel KELAS, GURU dan MATA_PELAJARAN. Dari definisi key ini kita dapat mengetahui istilah MASTER-DETAIL.</td>
</tr>
<tr>
<td valign="top">Alternate Key (Unique Key)</td>
<td style="padding-left:10px;" valign="top">:</td>
<td style="padding-left:10px;" valign="top">Key ini sebenarnya hampir sama dengan fungsi <em><strong>primary key</strong></em> yaitu berjenis <em><strong>unique key</strong></em>. Maksudnya adalah mungkin saja <em><strong>primary key</strong></em> yang kita buat pada suatu tabel adalah merupakan <em>autonumber</em> (angka yang bertambah terus-menerus ketika proses <em>insert</em> data, sehingga tidak dimungkinkan terdapat nilai yang sama), dikarenakan tidak diperbolehkan ada dua <em><strong>primary key</strong></em> maka dapat dibantu oleh <em><strong>alternate key</strong></em> ini sebagai penanda unique-nya sebuah record dengan record lain. Dalam sebuah tabel diperbolehkan <strong>lebih dari satu</strong> <em><strong>alternate key</strong></em>.</td>
</tr>
<tr>
<td valign="top">Non Unique Key</td>
<td style="padding-left:10px;" valign="top">:</td>
<td style="padding-left:10px;" valign="top">Key yang bisa lebih dari satu dalam sebuah tabel dan tidak mendefinisikan <em>unique</em> antar record di dalam table tersabut. Key ini biasa digunakan untuk membantu proses pencarian (<em>select</em>) data pada sebuah kolom yang sering digunakan untuk proses tersebut.</td>
</tr>
</tbody>
</table>
<p>Setelah mengetahui definisi &#8220;mudah&#8221; dari setiap key maka ada beberapa tips yang harus diperhatikan dalam pemberian key pada kolom-kolom dalam sebuah tabel :</p>
<ol>
<li>Pastikan sebuah tabel mempunyai <em><strong>primary key</strong></em>.</li>
<li>Pastikan <em><strong>primary key</strong></em> tersebut mewakili <em>unique</em>-nya sebuah record.</li>
<li>Ada baiknya menjadikan satu kolom saja untuk sebuah primary key sebagai <em>autonumber</em> mewakili beberapa kolom yang merupakan <em>unique</em>-nya record. Mis : tabel BELAJAR mempunyai tiga kolom sebagai <em><strong>primary key</strong></em>, yaitu : NIG, Kode_MP, dan Kelas_ID, maka ketiga kolom tersebut dapat dijadikan <em><strong>alternate key</strong></em>, dan untuk <em><strong>primary key</strong></em>-nya dibuatkan satu kolom lagi, yaitu Belajar_ID. Ini akan mempermudah jika ada tabel yang mengambil <em><strong>primary key</strong></em> pada tabel BELAJAR sebagai <strong><em>foreign key</em></strong> tabel tersebut.</li>
<li>Jangan terlalu banyak dalam pembuatan <em><strong>alternate key</strong></em>, karena key ini akan memperlambat proses <em>insert</em> dan <em>update</em> pada tabel tersebut. Secara logika <em><strong>alternate key</strong></em> akan mengecek ke-<em>unique</em>-kan seluruh record dari setiap record baru yang di-<em>insert</em> atau perubahan data pada record. Bayangkan jika datanya cukup besar&#8230; dan banyak <em><strong>alternate key</strong></em>&#8230; !!</li>
<li>Pilihlah dengan baik <em><strong>alternate key</strong></em> karena <em><strong>alternate key</strong></em> akan mempermudah dan mempercepat proses <em>select</em> jika digunakan. Maksudnyanya adalah KOLOM-KOLOM dalam <em><strong>alternate key</strong></em> tersebut yang digunakan.</li>
<li>Gunakan <em><strong>Non-unique key</strong></em> untuk kolom yang sering digunakan dalam proses <em>select</em>.</li>
<li>Gunakan penamaan key-key tersebut dengan penamaan yang baik dan mudah diidentifikasikan, seperti <em>BELAJAR_PK</em> (<em><strong>primary key</strong></em> tabel BELAJAR), <em>BELAJAR#GURU_FK</em> (<em><strong>foreign key</strong></em> pada tabel BELAJAR dari tabel GURU), dan <em>BELAJAR_AK</em> (<em><strong>alternate key</strong></em> tabel BELAJAR)</li>
</ol>
<p>Untuk cara pembuatan key-key tersebut dapat dilihat dari contoh berikut :</p>
<table class="MsoTableGrid" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0" width="578">
<tbody>
<tr>
<td style="border:1pt solid windowtext;font-family:courier;padding-left:30px;background-color:#CCCCCC;" valign="top"><span style="color:#008000;">/*==============================================================*/<br />
/* Table: BELAJAR                                               */<br />
/*==============================================================*/</span><span style="color:#0000ff;"> </span></p>
<p><span style="color:#0000ff;">create table</span> BELAJAR  (<br />
NIG                  <span style="color:#ff0000;">VARCHAR2</span>(32)                     <span style="color:#0000ff;">not null</span>,<br />
KODE_MP              <span style="color:#ff0000;">VARCHAR2</span>(32)                     <span style="color:#0000ff;">not null</span>,<br />
KELAS_ID             <span style="color:#ff0000;">VARCHAR2</span>(32)                     <span style="color:#0000ff;">not null</span>,<br />
HARI <span style="color:#ff0000;">VARCHAR2</span>(32) <span style="color:#0000ff;">not null</span>,<br />
<span style="color:#0000ff;">constraint </span>PK_BELAJAR <span style="color:#0000ff;">primary key</span> (NIG, KODE_MP, KELAS_ID),<br />
<span style="color:#0000ff;">constraint </span>BELAJAR#GURU_FK <span style="color:#0000ff;">foreign key</span> (NIG)<br />
<span style="color:#0000ff;">references </span>GURU (NIG),<br />
<span style="color:#0000ff;">constraint </span>BELAJAR#MATA_PELAJARAN_FK <span style="color:#0000ff;">foreign key</span> (KODE_MP)<br />
<span style="color:#0000ff;">references </span>MATA_PELAJARAN (KODE_MP),<br />
<span style="color:#0000ff;">constraint </span>BELAJAR#KELAS_FK <span style="color:#0000ff;">foreign key</span> (KELAS_ID)<br />
<span style="color:#0000ff;">references </span>KELAS (KELAS_ID)<br />
)<br />
/</td>
</tr>
</tbody>
</table>
<p>Atau bisa ditulis dengan :</p>
<table class="MsoTableGrid" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0" width="578">
<tbody>
<tr>
<td style="border:1pt solid windowtext;font-family:courier;padding-left:30px;background-color:#CCCCCC;" valign="top"><span style="color:#008000;">/*==============================================================*/<br />
/* Table: BELAJAR                                               */<br />
/*==============================================================*/</span></p>
<p><span style="color:#0000ff;">create table</span> BELAJAR  (<br />
NIG                  <span style="color:#ff0000;">VARCHAR2</span>(32)                     <span style="color:#0000ff;">not null</span>,<br />
KODE_MP              <span style="color:#ff0000;">VARCHAR2</span>(32)                     <span style="color:#0000ff;">not null</span>,<br />
KELAS_ID             <span style="color:#ff0000;">VARCHAR2</span>(32)                     <span style="color:#0000ff;">not null</span>,<br />
HARI <span style="color:#ff0000;">VARCHAR2</span>(32) <span style="color:#0000ff;">not null</span>);</p>
<p><span style="color:#0000ff;">ALTER TABLE</span> BELAJAR<br />
<span style="color:#0000ff;">ADD </span><span style="color:#0000ff;">constraint</span> PK_BELAJAR <span style="color:#0000ff;">primary key</span> (NIG, KODE_MP, KELAS_ID);</p>
<p><span style="color:#0000ff;">ALTER TABLE </span>BELAJAR<br />
<span style="color:#0000ff;">ADD constraint </span>BELAJAR#GURU_FK <span style="color:#0000ff;">foreign key</span> (NIG)<br />
<span style="color:#0000ff;">references </span>GURU (NIG);</p>
<p><span style="color:#0000ff;">ALTER TABLE </span>BELAJAR<br />
<span style="color:#0000ff;">ADD constraint </span>BELAJAR#MATA_PELAJARAN_FK <span style="color:#0000ff;">foreign key </span>(KODE_MP)<br />
<span style="color:#0000ff;">references </span>MATA_PELAJARAN (KODE_MP);</td>
</tr>
</tbody>
</table>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[MySQL foreign key constraint fails even when data is correct]]></title>
<link>http://prblm.wordpress.com/2009/06/11/mysql-foreign-key-constraint-fails-even-when-data-is-correct/</link>
<pubDate>Thu, 11 Jun 2009 10:44:18 +0000</pubDate>
<dc:creator>aakashd</dc:creator>
<guid>http://prblm.wordpress.com/2009/06/11/mysql-foreign-key-constraint-fails-even-when-data-is-correct/</guid>
<description><![CDATA[prblm: I have a parent child table pair, and trying to insert data into child table which exists in ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><strong>prblm:</strong> I have a parent child table pair, and trying to insert data into child table which exists in parent table. The datatype and length of field etc etc is exactly same. But still MySQL throws constriant violation error.</p>
<p><strong>solution</strong>:Its not a universal solution as such, but please check if the constriant was created properly. If at the time of constraint creation FOREIGN_KEY_CHECKS was set to 0/false; the constraint definition would be stored in information_schema without evaluating if the table/column/schema names used even exists.</p>
<p><strong>description</strong>:Though at first glance the behavior of not checking the schema name looks sinister, the very flag FOREIGN_KEY_CHECKS tells MySQL that constriants are not to be checked. This would simple use the table/constraint creation script to dump the definition in information_schema and would be used to evaluate the constraint when activated.</p>
<p>And as the MySQL error descriptions are as bad as they can be, whatever failure happens with data insertion in case of constraint evaluation is coined as constriant failure.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[FOREIGN KEY Constraint]]></title>
<link>http://e12a.wordpress.com/2009/05/13/foreign-key-constraint/</link>
<pubDate>Thu, 14 May 2009 06:21:11 +0000</pubDate>
<dc:creator>e12x</dc:creator>
<guid>http://e12a.wordpress.com/2009/05/13/foreign-key-constraint/</guid>
<description><![CDATA[Jika kita membuat tabel dalam MySQL dengan enggine InnoDb, maka kita bisa menggunakan FOREIGN KEY Co]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Jika kita membuat tabel dalam MySQL dengan enggine InnoDb, maka kita bisa menggunakan FOREIGN KEY Constrain. Salah satu manfaanya adalah, misalkan ada tabel induk A dan tabel anak B. Jika kita menghapus record dalam tabel induk A, maka dalam tabel B yang terdapat nilai dalam tabel A akan dihapus.Sintaksnya adalah seperti ini:</p>
<pre>[CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name, ...)
REFERENCES tbl_name (index_col_name, ...)
[ON DELETE {RESTRICT &#124; CASCADE &#124; SET NULL &#124; NO ACTION}]
[ON UPDATE {RESTRICT &#124; CASCADE &#124; SET NULL &#124; NO ACTION}]</pre>
<p>Keterangan:</p>
<p><em>CASCADE</em>: menghapus atau meng-update baris data dalam tabel induk secara otomatis atau mengupdate baris yang sesuai dalam tabel anak  <em></em></p>
<p><em>SET NULL</em>: menghapus atau meng-update baris data dalam tabel induk dan men-set kolom/beberapa kolom dalam tabel anak menjadi null. hal ini akan valid jika kolom foreign key tidak memiliki not null. kita boleh menggunakan ON DELETE SET NULL dan ON UPDAE</p>
<p>SET NULL jika kita gunakan SET NULL, pastikan bahwa anda tidak mendeklarasikan kolom dalam tabel anak dalam NOT NULL  <em>NO ACTION</em>: dalam standar SQL, NO ACTION berarti tidak diprbolehkan menghapus, merubah nilai primary key jika ada foreign key yang berhubungan dalam tabel referensi. innodb menolak  untuk menghapus atau merubah data pada tabel induk</p>
<p><em>RESCRICT</em>: tidak memperbolehkan menghapus atau merubah pada tabel induk. ini hampir sama sama dengan NO ACTION  <em>SET DEFAULT</em>: aksi ini dibutuhkan oleh parser, tapi InnoDB menolak definisi tabel berupa ON DELETE SET DEFAULT atau ON DELETE SET DEFAULT klausa.  OK, biar lebih jelas <!--more-->anda bisa mencoba beberapa percobaan berikut:</p>
<p># buat database perpustakaan</p>
<pre>CREATE DATABASE perpustakaan;

USE perpustakaan;</pre>
<p>#buat tabel pengarang</p>
<pre>create table pengarang (
id int(5) not null,
nama varchar(30) not null,
alamat varchar(50),
primary key(id)
) engine=innodb;</pre>
<p># buat tabel penerbit</p>
<pre>create table penerbit(
id int(5) not null auto_increment,
nama varchar(30) not null,
alamat varchar(50),
primary key(id)
)engine=innodb;</pre>
<p># buat tabel buku</p>
<pre>create table buku (
 id int(5) not null,
 id_penerbit int(5),
 id_pengarang int(5),
 isbn varchar(20),
 index (id_penerbit),
 foreign key (id_penerbit) references penerbit(id) on update cascade on delete restrict,
 index (id_pengarang),
 foreign key (id_pengarang) references pengarang(id)
 ) engine=innodb;</pre>
<p># masukkan data ke dalam tabel penerbit</p>
<pre>insert into penerbit values(null, 'Intimedia', 'jakarta');
 insert into penerbit values(null, 'Tiara Wacana', 'Yogyakarta');
 insert into penerbit values(null, 'Diva Press', 'Yogyakarta');</pre>
<p># masukkan data ke dalam tabel pengarang</p>
<pre>insert into pengarang values(1, 'Abdul kodir', 'Yogyakarta');
 insert into pengarang values(2, 'Salim A Fillah', 'Yogyakarta');
 insert into pengarang values(3, 'Fathan Funtastic', 'Yogyakarta');</pre>
<p>Sekarang mari kita lakukan beberapa percobaan</p>
<p># percobaan 1</p>
<pre>insert into buku values(1,6,9,'12345');</pre>
<p>Error yang akan muncul kurang lebih seperti ini: <span style="color:red;"> ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`learn_mysql`.`buku`, CONSTRAINT `buku_ibfk_1` FOREIGN KEY (`id_penerbit`) REFERENCES `penerbit` (`id`) ON UPDATE CASCADE) </span> Mengapa demikian? Hal ini dikarenakan kita ingin mencoba memasukkan nilai id(id_pengarang, id_penerbit) yang didak ada di dalam tabel pengarang maupun tabel penerbit.</p>
<p># percobaan 2</p>
<pre>insert into buku values(1,2,1,'12345');</pre>
<p>Kali ini tidak akan terjadi eror, hal ini karen nilai 2 dan 1 pada perintah di atas sudah terdaftar dalam kedua tabel induk: pengarang, penerbit cobalah untuk melihat isi tabel buku:</p>
<pre>select * from buku;
+----+-------------+--------------+-------+
&#124; id &#124; id_penerbit &#124; id_pengarang &#124; isbn  &#124;
+----+-------------+--------------+-------+
&#124;  1 &#124;           2 &#124;            1 &#124; 12345 &#124;
+----+-------------+--------------+-------+</pre>
<p>#percobaan 3</p>
<pre>delete from penerbit where id=2;</pre>
<p>eror yang akan muncul adalah: <span style="color:red;"> ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`learn_mysql`.`buku`, CONSTRAINT `buku_ibfk_1` FOREIGN KEY (`id_penerbit`) REFERENCES `penerbit` (`id`) ON UPDATE CASCADE) kenapa? karena kita mendefinisikan pada tabel buku bahwa id dari penerbit adalah ON DELETE RESTRICT, </span></p>
<p># percobaan 4</p>
<pre>update penerbit set id=7 where id=2;</pre>
<p>kali ini tidak akan muncul eror tapi cobalah utuk melihat isi tabel buku berikut:</p>
<pre>select * from buku;

+----+-------------+--------------+-------+
&#124; id &#124; id_penerbit &#124; id_pengarang &#124; isbn  &#124;
+----+-------------+--------------+-------+
&#124;  1 &#124;           7 &#124;            1 &#124; 12345 &#124;
+----+-------------+--------------+-------+</pre>
<p>jika kita lihat, id_penerbit pada tabel buku juga akan berubah.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Oracle 10g - Add Constraint Foreign Key]]></title>
<link>http://dbaborges.wordpress.com/2009/05/13/fk-add-constraint-oracle/</link>
<pubDate>Thu, 14 May 2009 01:42:45 +0000</pubDate>
<dc:creator>geovansb</dc:creator>
<guid>http://dbaborges.wordpress.com/2009/05/13/fk-add-constraint-oracle/</guid>
<description><![CDATA[What´s a Foreign Key: A foreign key is a column in a table that does NOT uniquely identify rows in t]]></description>
<content:encoded><![CDATA[What´s a Foreign Key: A foreign key is a column in a table that does NOT uniquely identify rows in t]]></content:encoded>
</item>
<item>
<title><![CDATA[Buwat Foreign Key di PHPmyadmin???]]></title>
<link>http://mdram.wordpress.com/2009/04/29/buwat-foreign-key-di-phpmyadmin/</link>
<pubDate>Wed, 29 Apr 2009 04:56:47 +0000</pubDate>
<dc:creator>@doen</dc:creator>
<guid>http://mdram.wordpress.com/2009/04/29/buwat-foreign-key-di-phpmyadmin/</guid>
<description><![CDATA[ 1. Konversi Tipe database dari MyISAM ke InnoDB 2. Buat index dari field yang akan dijadikan foreig]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><span style="font-size:12pt;font-family:&#34;"> <img class="aligncenter size-full wp-image-748" title="cafe" src="http://mdram.wordpress.com/files/2009/04/cafe.gif" alt="cafe" width="50" height="50" />1. Konversi Tipe database dari MyISAM ke InnoDB</span></p>
<p><span style="font-size:12pt;font-family:&#34;">2. Buat index dari field yang akan dijadikan foreign key</span></p>
<p><span style="font-size:12pt;font-family:&#34;">3. Kemudian pilih <strong>relation view </strong>arahkan field yg jadi index ke field tabel yg dijadikan Primary key.</span></p>
<p><span style="font-size:12pt;font-family:&#34;">Screenshoot gambar ntar nyusul. </span></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Remove FK CONSTRAINT]]></title>
<link>http://tehminaqureshi.wordpress.com/2009/04/21/remove-fk-constraint/</link>
<pubDate>Tue, 21 Apr 2009 14:12:35 +0000</pubDate>
<dc:creator>Tehmina</dc:creator>
<guid>http://tehminaqureshi.wordpress.com/2009/04/21/remove-fk-constraint/</guid>
<description><![CDATA[IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N&#8217;[dbo].[FK_Name]&#8216;]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>IF  EXISTS (SELECT * FROM sys.foreign_keys<br />
WHERE object_id = OBJECT_ID(N&#8217;[dbo].[FK_Name]&#8216;)<br />
AND parent_object_id = OBJECT_ID(N&#8217;[dbo].[ChildTableName]&#8216;))<br />
ALTER TABLE [dbo].[ChildTableName]<br />
DROP CONSTRAINT [FK_Name]<br />
GO<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>ALTER TABLE [dbo].[ChildTableName]  WITH CHECK ADD  CONSTRAINT [FK_Name] FOREIGN KEY([FKIDName])<br />
REFERENCES [dbo].[MasterTableName] ([MasterPKID])<br />
GO<br />
ALTER TABLE [dbo].[ChildTableName] CHECK CONSTRAINT [FK_Name]<br />
GO</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Falha na validação de Foreign Keys do SQL Server]]></title>
<link>http://faulog.wordpress.com/2009/04/03/falha-na-validacao-de-foreign-keys-do-sql-server/</link>
<pubDate>Fri, 03 Apr 2009 14:40:50 +0000</pubDate>
<dc:creator>faustoodilon</dc:creator>
<guid>http://faulog.wordpress.com/2009/04/03/falha-na-validacao-de-foreign-keys-do-sql-server/</guid>
<description><![CDATA[/* Autor : Fausto Odilon Data : 03/04/2009 Descrição: Este Script demonstra uma falha de validação d]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>/*<br />
Autor : Fausto Odilon<br />
Data : 03/04/2009<br />
Descrição:<br />
Este Script demonstra uma falha de validação de Foreign Keys do SQL Server.<br />
Quando uma Foreign Key é composta por mais de um campo com preenchimento opcional (NULL),<br />
se um dos campos for informado como nulo, os demais não serão validados, permitindo<br />
qualquer valor, ou seja, a inclusão de lixos na tabela relacionada.<br />
*/</p>
<p>create table TMP_Teste_PK<br />
(<br />
Campo1 int NOT NULL,<br />
Campo2 int NOT NULL,<br />
Campo3 int NOT NULL,<br />
CONSTRAINT PK_TMP_Teste_PK<br />
PRIMARY KEY CLUSTERED (Campo1, Campo2, Campo3)<br />
)</p>
<p>insert into TMP_Teste_PK<br />
select 1, 1, 1<br />
union select 1, 2, 1<br />
union select 1, 3, 1<br />
union select 2, 1, 2<br />
union select 2, 2, 2<br />
union select 3, 1, 2<br />
union select 3, 2, 2</p>
<p>create table TMP_Teste_FK<br />
(<br />
Campo1 int NULL,<br />
Campo2 int NULL,<br />
Campo3 int NULL,<br />
CONSTRAINT PK_TMP_Teste_FK<br />
foreign KEY (Campo1, Campo2, Campo3)<br />
references TMP_Teste_PK (Campo1, Campo2, Campo3)<br />
)</p>
<p>truncate table TMP_Teste_FK<br />
insert into TMP_Teste_FK<br />
select 1, 1, 1 &#8212; Dados OK<br />
union select 1, 2, 1 &#8212; Dados OK<br />
union select 2, 2, 2 &#8212; Dados OK<br />
union select 2, NULL, 1 &#8212; Dados Inválidos<br />
union select 5, NULL, 2 &#8212; Dados Inválidos<br />
union select -99, NULL, 3 &#8212; Dados Inválidos<br />
union select NULL, 98, -17 &#8212; Dados Inválidos</p>
<p>select * from TMP_Teste_FK</p>
<p>drop table TMP_Teste_FK<br />
drop table TMP_Teste_PK</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Descobrindo a definição de chave primária (primary key) e chave estrangeira (foreign key)]]></title>
<link>http://jotacomm.wordpress.com/2009/03/23/descobrindo-a-definicao-de-chave-primaria-primary-key-e-chave-estrangeira-foreign-key/</link>
<pubDate>Mon, 23 Mar 2009 00:44:04 +0000</pubDate>
<dc:creator>jotacomm</dc:creator>
<guid>http://jotacomm.wordpress.com/2009/03/23/descobrindo-a-definicao-de-chave-primaria-primary-key-e-chave-estrangeira-foreign-key/</guid>
<description><![CDATA[Olá, pessoal Na última semana surgiu uma pergunta na lista pgbr-geral sobre como descobrir a definiç]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Olá, pessoal</p>
<p>Na última semana surgiu uma pergunta na lista <span class="gI"><em>pgbr-geral</em> sobre como descobrir a definição das  restrições  (constraints) de chave primária (primary key)  e chave estrangeira (foreign key).  Então aproveito para escrever um pouquinho sobre o assunto.<br />
</span></p>
<p><span class="gI">Essa informação não é encontrada diretamente nas tabelas e visões do catálogo do PostgreSQL, mas sim através de uma função chamada pg_get_constraintdef(oid), onde o parâmetro oid é o oid da constraint e que pode ser encontrado na tabela pg_constraint. Por exemplo, existe uma visão chamada pg_indexes que mostra as definições dos índices, porém se pararmos para analisar esta consulta veremos que para apresentar a definição dos índices é utilizada uma função chamada pg_get_indexdef(oid) semelhante a função usada para extrair a definição das restrições (constraints).<br />
</span></p>
<p><span class="gI">Abaixo segue a consulta para identificar o nome da tabela e suas definições de chave primária (primary key) e chave estrangeira (foreing key). Para encontrar essa informação é necessário o uso das tabelas de sistema pg_class e pg_constraint. Coloquei também a tabela pg_namespace que é onde são armazenados os esquemas existentes do PostgreSQL.<br />
</span></p>
<p>SELECT pg_class.relname AS nome_da_tabela,</p>
<p>pg_get_constraintdef(pg_constraint.oid) AS definicao_da_restricao</p>
<p>FROM pg_namespace JOIN pg_class ON pg_namespace.oid=pg_class.relnamespace</p>
<p>JOIN pg_constraint ON pg_class.oid=pg_constraint.conrelid</p>
<p>WHERE pg_namespace.nspname=&#8217;public&#8217;</p>
<p>AND pg_class.relkind=&#8217;r&#8217;</p>
<p>ORDER BY pg_class.relname;</p>
<p>O resultado desta consulta apresenta o nome da tabela e a sua respectiva definição de chave primária (primary key) e chave estrangeira (foreign key). Caso a tabela não possua chave primária e/ou chave estrangeira a mesma não será retornada por esta consulta. Neste caso seria necessário substituir o INNER JOIN por um LEFT OUTER JOIN. A palavra OUTER no LEFT OUTER JOIN é opcional.</p>
<p>E a sua implementação ficaria assim:</p>
<p>SELECT pg_class.relname AS nome_da_tabela,</p>
<p>pg_get_constraintdef(pg_constraint.oid) AS definicao_da_restricao</p>
<p>FROM pg_namespace JOIN pg_class ON pg_namespace.oid=pg_class.relnamespace</p>
<p>LEFT OUTER JOIN pg_constraint ON pg_class.oid=pg_constraint.conrelid</p>
<p>WHERE pg_namespace.nspname=&#8217;public&#8217;</p>
<p>AND pg_class.relkind=&#8217;r&#8217;</p>
<p>ORDER BY pg_class.relname;</p>
<p>Na cláusula <strong>WHERE</strong> existem duas restrições: <strong>pg_namespace.nspname=&#8217;public&#8217;</strong> restringe em qual esquema serão procurados os objetos, neste caso apenas no esquema public. Se for necessário procurar em mais de um esquema pode-se substituir a condição <strong>pg_namespace.nspname=&#8217;public&#8217;</strong> por <strong>pg_namespace.nspname IN (&#8216;public&#8217;, &#8216;outro_esquema&#8217;)</strong>. A condição <strong>pg_class.relkind=&#8217;r&#8217;</strong> restringe que só serão pesquisados os objetos do tipo tabela. Esta restrição é importante pois a tabela pg_class armazena outros objetos como: índices, seqüências, visões, tipos compostos e tabelas toast. Esta condição é necessária devido ao join com a tabela pg_namespace. Se essa junção for retirada não é necessária esta restrição.</p>
<p>Se for de interesse é possível mostrar o nome da restrição (constraint) através do atributo conname  que está armazenado na tabela pg_constraint.</p>
<p>Era isso. Fiquem a vontade para comentários.</p>
<p>Abraços</p>
<p><span class="gI"><br />
</span></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[SQL Server - Criação de tabelas com chave estrangeira]]></title>
<link>http://marceloabibcardoso.wordpress.com/2009/03/16/sql-server-criacao-de-tabelas-com-chave-estrangeira/</link>
<pubDate>Mon, 16 Mar 2009 20:41:51 +0000</pubDate>
<dc:creator>mabib</dc:creator>
<guid>http://marceloabibcardoso.wordpress.com/2009/03/16/sql-server-criacao-de-tabelas-com-chave-estrangeira/</guid>
<description><![CDATA[Olá Pessoal, Hoje estaremos abordando a criação de uma tabela com chave estrangeira ou foreign key. ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Olá Pessoal,</p>
<p>Hoje estaremos abordando a criação de uma tabela com chave estrangeira ou foreign key.</p>
<p>Abordaremos então:</p>
<p>- O que é uma chave estrangeira(FK)?</p>
<p>- Colocando em prática</p>
<p>- Por que usar?</p>
<p>Bom pra começar chave estrangeira ou foreign key, é a relação entre duas tabelas tendo na tabela “mãe” a referência da tabela “filho”.</p>
<p>Ficou confuso?</p>
<p>vamos exemplificar, todos nós sabemos que um cliente precisa morar em uma cidade, então temos a tabela “mãe” que é a Cliente, onde nos atributos tem a referência da tabela filho que é a Cidade, conforme mostro a seguir:</p>
<p>Cliente                        Cidade</p>
<p>(                                  (</p>
<p>ClienteId(PK)                CidadeId(PK)</p>
<p>Nome                          Cidade</p>
<p>Endereco                     Estado</p>
<p>Telefone                  )</p>
<p>CidadeId(FK)</p>
<p>)</p>
<p>reparem que coloquei uma coluna chamada CidadeId, o que é essa CidadeId? Nada mais é que a chave primaria da tabela Cidade e a chave estrangeira da tabela Clientes.</p>
<p>Pois na hora de inserir registros na tabela de Clientes, ao invés de inserirmos Campinas, Vinhedo, Valinhos, nós armazenaremos a referência delas na tabela de Cidade.</p>
<p>CidadeId    Cidade        Estado</p>
<p>1            Campinas       SP</p>
<p>2            Valinhos        SP</p>
<p>3            Vinhedo         SP</p>
<p>Na tabela de Cliente só iremos armazenar 1,2 ou 3, que são os registros existentes na tabela de Cidade, caso um “engraçadinho” tente inserir um 4 por exemplo, sem que ele esteja na tabela de Cidade dará um erro de chave estrangeira, não sendo possível a gravação.</p>
<p>Agora entendi, mas como crio uma chave estrangeira?</p>
<p>Simples, iremos criar as tabelas Cliente e Cidade primeiro. Uma boa prática para criação de tabelas, é sempre começar pelas tabelas simples, ou seja, aquelas que não possuem chave estrangeira.</p>
<p>CREATE TABLE Cidade</p>
<p>(</p>
<p>CidadeId    int not null IDENTITY(1,1),</p>
<p>Cidade        nvarchar(64) not null CONSTRAINT UQ_Cidade_Cidade UNIQUE,</p>
<p>Estado        char(2) not null,</p>
<p>CONSTRAINT PK_Cidade_CidadeId PRIMARY KEY(CidadeId)</p>
<p>)</p>
<p>CREATE TABLE Cliente</p>
<p>(</p>
<p>ClienteId    int not null IDENTITY(1,1),</p>
<p>Nome        nvarchar(128) not null,</p>
<p>Endereco    nvarchar(128) not null,</p>
<p>CidadeId    int not null,</p>
<p>CONSTRAINT PK_Cidade_ClienteId PRIMARY KEY(ClienteId),</p>
<p>CONSTRAINT FK_Cliente_Cidade_CidadeId FOREIGN KEY(CidadeId) REFERENCES Cidade(CidadeId)</p>
<p>)</p>
<p>Repare que na tabela Cliente, eu crio a chave estrangeira, mas esse não é o único jeito de criar. Poderiamos ter criado as tabelas Cliente/Cidade, e depois usar a keyword ALTER TABLE para estar adicionando a chave, conforme mostro abaixo:</p>
<p>ALTER TABLE Cliente</p>
<p>ADD CONSTRAINT FK_Cliente_Cidade_CidadeId</p>
<p>FOREIGN KEY(CidadeId)</p>
<p>REFERENCES Cidade(CidadeId)</p>
<p>Bom, já entendi o que é, já criei a chave, mas por que utiliza-la?</p>
<p>Pois bem, utilizamos ela para:</p>
<p>* Manter a concistência do banco de dados</p>
<p>* Para criação de indices, na qual estaremos vendo adiante.</p>
<p>* Para otimização do banco de dados.</p>
<p>* Para facilitar a manutenção.</p>
<p>Pessoal, por hoje é só, quem tiver dúvidas no assunto, pode comentar que eu respondo ou ainda me mandar e-mail: marcelinho.ruliz@gmail.com</p>
<p>Abraço,</p>
<p>Té mais.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Cascade Delete in SQL Server]]></title>
<link>http://mycodelines.wordpress.com/2009/02/24/cascade-delete-in-sql-server/</link>
<pubDate>Tue, 24 Feb 2009 10:25:51 +0000</pubDate>
<dc:creator>Lakshmi Sravanthi Chowdam</dc:creator>
<guid>http://mycodelines.wordpress.com/2009/02/24/cascade-delete-in-sql-server/</guid>
<description><![CDATA[This article comes to us from Tim Young. Tim writes &quot;One of the (few) very handy things about A]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>This article comes to us from <strong><a href="http://www.sqlteam.com/forums/pop_profile.asp?mode=display&#38;id=3203">Tim Young</a></strong>. Tim writes &#34;<em>One of the (few) very handy things about Access is the cascade delete function. If you delete a record from a parent table, all relating records in the child tables are also deleted. I couldn’t find any way of doing this in SQL Server 7, so I wrote a stored procedure for it.</em>&#34; Thanks for the article Tim!</p>
<p>Normally, if you try and delete a record from a table that is constrained by a foreign key, you’ll get an error message. This procedure checks for any foreign keys for the table, deletes any child records, then deletes the intended record.</p>
<p>It references the system tables sysforeignkeys, sysobjects and syscolumns. Sysforeignkeys does what it says on the tin – it’s a list of all foreign keys in the database. It doesn’t contain actual table and field names, instead it contains links to the sysobjects (tables, stored procedures, views etc) and syscolumns (fields).</p>
<p>The procedure works like this – if we want to delete a record from table X, we look in the sysforeignkeys table for all references where table X is the parent table. It may be involved in several such FK’s. All we do is recursively go through these FK’s, deleting the child table records that are linked to the record we want to delete.</p>
<p>For example,</p>
<p>- delete all records from table X where field1 equals &#8216;234&#8242;</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td valign="top" width="400">DELETE FROM Y WHERE Y_ID IN (SELECT Y_ID FROM X WHERE field1 = &#8216;234&#8242;)</td>
</tr>
</tbody>
</table>
<pre class="c#">- table Y is linked to X through the Y_ID field, so</pre>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td valign="top" width="400">DELETE FROM Y WHERE Y_ID IN (SELECT Y_ID FROM X WHERE field1 = &#8216;234&#8242;)</td>
</tr>
</tbody>
</table>
<pre>- table Z is linked to Y through the Z_ref field</pre>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td valign="top" width="400">DELETE FROM Z WHERE Z-ref IN&#160; <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; (SELECT Z_ref FROM Y WHERE Y_ID IN&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; (SELECT Y_ID FROM X WHERE field1 = &#8216;234&#8242; ) )</td>
</tr>
</tbody>
</table>
<p>As you can see from the above example, if one of the child tables is also involved in a FK constraint, we also need to delete the relating rows in it’s child tables.</p>
<p>Here’s the code for the procedure:</p>
<table cellspacing="0" cellpadding="2" width="67" border="1">
<tbody>
<tr>
<td valign="top" width="65">
<pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=CREATE&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">CREATE</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=Procedure&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">Procedure</a> spDeleteRows
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><span style="color:#008000;">/*
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">Recursive row delete procedure.
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"></pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

It deletes all rows in the table specified that 

conform to the criteria selected,

</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

while also deleting any child/grandchild records and 

so on.  This is designed to do the

</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

same sort of thing as Access's cascade delete function. 

It first reads the sysforeignkeys

</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

table to find any child tables, then deletes the 

soon-to-be orphan records from them using

</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

recursive calls to this procedure. Once all 

child records are gone, the rows are deleted

</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

from the selected table.   It is designed at this 

time to be run at the command line. It could

</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

also be used in code, but the printed output 

will not be available.

</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">*/</span>
</pre>
<pre style="font-size:12px;width:56.9%;font-family:consolas,&#39;height:30px;background-color:#ffffff;margin:0;">	(
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

	@cTableName <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=varchar&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">varchar</a>(50), <span style="color:#008000;">/* name of the table where </span>

<span style="color:#008000;">                                 rows are to be deleted */</span>

</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

	@cCriteria <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=nvarchar&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">nvarchar</a>(1000), <span style="color:#008000;">/* criteria used to </span>

<span style="color:#008000;">                                             delete the rows required */</span>

</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

	@iRowsAffected <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=int&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">int</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=OUTPUT&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">OUTPUT</a> <span style="color:#008000;">/* number of records </span>

<span style="color:#008000;">                                        affected by the delete */</span>

</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">	)
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=As&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">As</a>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=set&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">set</a> nocount <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=on&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">on</a>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=declare&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">declare</a> 	@cTab <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=varchar&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">varchar</a>(255), <span style="color:#008000;">/* name of the child table */</span>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">	@cCol <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=varchar&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">varchar</a>(255), <span style="color:#008000;">/* name of the linking field on the child table */</span>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">	@cRefTab <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=varchar&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">varchar</a>(255), <span style="color:#008000;">/* name of the parent table */</span>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

	@cRefCol <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=varchar&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">varchar</a>(255), <span style="color:#008000;">/* name of the linking field in the </span>

<span style="color:#008000;">                                   parent table */</span>

</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">	@cFKName <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=varchar&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">varchar</a>(255), <span style="color:#008000;">/* name of the foreign key */</span>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

	@cSQL <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=nvarchar&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">nvarchar</a>(1000), <span style="color:#008000;">/* query string passed to the sp_ExecuteSQL </span>

<span style="color:#008000;">                                     procedure */</span>

</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">	@cChildCriteria <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=nvarchar&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">nvarchar</a>(1000), <span style="color:#008000;">/* criteria to be used to delete
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">                                           records from the child table */</span>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">	@iChildRows <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=int&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">int</a> <span style="color:#008000;">/* number of rows deleted from the child table */</span>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"></pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><span style="color:#008000;">/* declare the cursor containing the foreign key constraint information */</span>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=DECLARE&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">DECLARE</a> cFKey <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=CURSOR&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">CURSOR</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=LOCAL&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">LOCAL</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=FOR&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">FOR</a>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=SELECT&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">SELECT</a> SO1.name <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=AS&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">AS</a> Tab,
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">       SC1.name <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=AS&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">AS</a> Col,
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">       SO2.name <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=AS&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">AS</a> RefTab,
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">       SC2.name <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=AS&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">AS</a> RefCol,
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">       FO.name <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=AS&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">AS</a> FKName
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=FROM&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">FROM</a> dbo.sysforeignkeys FK
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=INNER&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">INNER</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=JOIN&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">JOIN</a> dbo.syscolumns SC1 <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=ON&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">ON</a> FK.fkeyid = SC1.id
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">                              <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=AND&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">AND</a> FK.fkey = SC1.colid
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=INNER&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">INNER</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=JOIN&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">JOIN</a> dbo.syscolumns SC2 <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=ON&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">ON</a> FK.rkeyid = SC2.id
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">                              <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=AND&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">AND</a> FK.rkey = SC2.colid
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=INNER&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">INNER</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=JOIN&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">JOIN</a> dbo.sysobjects SO1 <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=ON&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">ON</a> FK.fkeyid = SO1.id
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=INNER&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">INNER</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=JOIN&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">JOIN</a> dbo.sysobjects SO2 <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=ON&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">ON</a> FK.rkeyid = SO2.id
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=INNER&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">INNER</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=JOIN&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">JOIN</a> dbo.sysobjects FO <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=ON&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">ON</a> FK.constid = FO.id
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=WHERE&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">WHERE</a> SO2.Name = @cTableName
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"></pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=OPEN&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">OPEN</a> cFKey
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=FETCH&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">FETCH</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=NEXT&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">NEXT</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=FROM&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">FROM</a> cFKey <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=INTO&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">INTO</a> @cTab, @cCol, @cRefTab, @cRefCol, @cFKName
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=WHILE&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">WHILE</a> @@FETCH_STATUS = 0
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">     <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=BEGIN&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">BEGIN</a>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

	<span style="color:#008000;">/* build the criteria to delete rows from the child table. </span>

<span style="color:#008000;">           As it uses the
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">           criteria passed to this procedure, it gets progressively larger with
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">           recursive calls */</span>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

	<a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=SET&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">SET</a> @cChildCriteria = @cCol + '<span style="color:#8b0000;"> in (SELECT [</span>' + 

                               @cRefCol + '<span style="color:#8b0000;">] FROM [</span>' +

&#160;
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">                              @cRefTab +'<span style="color:#8b0000;">] WHERE </span>' + @cCriteria + '<span style="color:#8b0000;">)</span>'
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">	<a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=print&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">print</a> '<span style="color:#8b0000;">Deleting records from table </span>' + @cTab
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">	<span style="color:#008000;">/* call this procedure to delete the child rows */</span>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">	<a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=EXEC&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">EXEC</a> spDeleteRows @cTab, @cChildCriteria, @iChildRows <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=OUTPUT&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">OUTPUT</a>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">	<a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=FETCH&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">FETCH</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=NEXT&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">NEXT</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=FROM&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">FROM</a> cFKey <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=INTO&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">INTO</a> @cTab, @cCol, @cRefTab, @cRefCol, @cFKName
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">     <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=END&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">END</a>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=Close&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">Close</a> cFKey
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=DeAllocate&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">DeAllocate</a> cFKey
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><span style="color:#008000;">/* finally delete the rows from this table and display the rows affected  */</span>
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=SET&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">SET</a> @cSQL = '<span style="color:#8b0000;">DELETE FROM [</span>' + @cTableName + '<span style="color:#8b0000;">] WHERE </span>' + @cCriteria
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=print&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">print</a> @cSQL
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;"><a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=EXEC&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">EXEC</a> <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=sp_ExecuteSQL&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">sp_ExecuteSQL</a> @cSQL
</pre>
<pre style="font-size:12px;width:100%;font-family:consolas,&#39;background-color:#ffffff;margin:0;">

<a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=print&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">print</a> '<span style="color:#8b0000;">Deleted </span>' + <a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=CONVERT&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">CONVERT</a>(<a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=varchar&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">varchar</a>, @@<a href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=ROWCOUNT&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99">ROWCOUNT</a>) +

 '<span style="color:#8b0000;"> records from table </span>' + @cTableName

</pre>
</pre>
</td>
</tr>
</tbody>
</table>
<p><span style="color:#ff00ff;">&#160;</span></p>
<p>In the above scenario, we were trying to perform the following :</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td valign="top" width="400">DELETE FROM X WHERE field1 = &#8216;234&#8242;</td>
</tr>
</tbody>
</table>
<p>Using this procedure, we would use the following command:</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td valign="top" width="400">exec spDeleteRows &#8216;X&#8217;, &#8216;field1 = &#8221;234&#8221;&#8217;, 0</td>
</tr>
</tbody>
</table>
<p>I hope this procedure has been of use.</p>
<p>Source: <a href="http://www.sqlteam.com/article/performing-a-cascade-delete-in-sql-server-7" target="_blank">http://www.sqlteam.com/article/performing-a-cascade-delete-in-sql-server-7</a></p>
<div class="wlWriterEditableSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:05c253f9-9428-4ba7-a599-8c9f80247271" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a href="http://technorati.com/tags/Cascade" rel="tag">Cascade</a>,<a href="http://technorati.com/tags/Delete" rel="tag">Delete</a>,<a href="http://technorati.com/tags/Cascade+Delete+procedure" rel="tag">Cascade Delete procedure</a>,<a href="http://technorati.com/tags/Cascade+Delete+Records" rel="tag">Cascade Delete Records</a>,<a href="http://technorati.com/tags/parent+table" rel="tag">parent table</a>,<a href="http://technorati.com/tags/child+table" rel="tag">child table</a>,<a href="http://technorati.com/tags/foreign+key" rel="tag">foreign key</a>,<a href="http://technorati.com/tags/primary+key" rel="tag">primary key</a>,<a href="http://technorati.com/tags/DBMS" rel="tag">DBMS</a>,<a href="http://technorati.com/tags/SQL+server" rel="tag">SQL server</a>,<a href="http://technorati.com/tags/database" rel="tag">database</a>,<a href="http://technorati.com/tags/FROM" rel="tag">FROM</a>,<a href="http://technorati.com/tags/WHERE" rel="tag">WHERE</a>,<a href="http://technorati.com/tags/SELECT" rel="tag">SELECT</a>,<a href="http://technorati.com/tags/constraint" rel="tag">constraint</a>,<a href="http://technorati.com/tags/CREATE" rel="tag">CREATE</a>,<a href="http://technorati.com/tags/JOIN" rel="tag">JOIN</a>,<a href="http://technorati.com/tags/OPEN" rel="tag">OPEN</a>,<a href="http://technorati.com/tags/FETCH" rel="tag">FETCH</a>,<a href="http://technorati.com/tags/FETCH_STATUS" rel="tag">FETCH_STATUS</a>,<a href="http://technorati.com/tags/BEGIN" rel="tag">BEGIN</a>,<a href="http://technorati.com/tags/EXEC" rel="tag">EXEC</a>,<a href="http://technorati.com/tags/DeAllocate" rel="tag">DeAllocate</a>,<a href="http://technorati.com/tags/CONVERT" rel="tag">CONVERT</a>,<a href="http://technorati.com/tags/ROWCOUNT" rel="tag">ROWCOUNT</a>,<a href="http://technorati.com/tags/sysobjects" rel="tag">sysobjects</a>,<a href="http://technorati.com/tags/syscolumns" rel="tag">syscolumns</a>,<a href="http://technorati.com/tags/sp_ExecuteSQL" rel="tag">sp_ExecuteSQL</a></div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Relational Model]]></title>
<link>http://mycodelines.wordpress.com/2009/02/09/relational-model/</link>
<pubDate>Mon, 09 Feb 2009 12:30:45 +0000</pubDate>
<dc:creator>Lakshmi Sravanthi Chowdam</dc:creator>
<guid>http://mycodelines.wordpress.com/2009/02/09/relational-model/</guid>
<description><![CDATA[All data are represented as tables. o The results of any given query are just another table! Tables ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>All data are represented as tables.</p>
<p>o The results of any given query are just another table!    <br />Tables are comprised of rows and columns     <br />Rows and columns are (officially) unordered (i.e., the order in which rows and columns are referenced does not matter).</p>
<p>o Rows are sorted only upon request. Otherwise, their order is arbitrary, and may change for a dynamic database</p>
<p>o Column order is determined by each query    <br />Each table has a primary key, a unique identifier constructed from one or more columns</p>
<p>Most primary keys are a single column (e.g., TOWN_ID)     <br />A table is linked (joined) to another by including the other table&#8217;s primary key. Such an included column is called a foreign key. Primary keys and foreign keys are the most important concepts in database design.</p>
<p>Relational database components include:</p>
<ul>
<li>Table </li>
<li>Row </li>
<li>Column </li>
<li>Field </li>
<li>Primary key </li>
<li>Foreign key </li>
</ul>
<p><a href="http://mycodelines.files.wordpress.com/2009/02/image2.png"><img title="image" style="display:block;float:none;margin-left:auto;margin-right:auto;border-width:0;" height="262" alt="image" src="http://mycodelines.files.wordpress.com/2009/02/image-thumb2.png?w=373&#038;h=262" width="373" border="0" /></a></p>
<p><i>A Table</i> is a basic storage structure of an RDBMS and consists of columns and rows. A table represents an entity. For example, the S_DEPT table stores information about the departments of an organization.</p>
<p><i>A Row</i> is a combination of column values in a table and is identified by a primary key. Rows are also known as records. For example, a row in the table S_DEPT contains information about one department.</p>
<p><a href="http://mycodelines.files.wordpress.com/2009/02/clip-image00219.jpg"><img title="clip_image002[19]" style="display:block;float:none;margin-left:auto;margin-right:auto;border-width:0;" height="297" alt="clip_image002[19]" src="http://mycodelines.files.wordpress.com/2009/02/clip-image00219-thumb.jpg?w=364&#038;h=297" width="364" border="0" /></a></p>
<p><i>A Column</i> is a collection of one type of data in a table. Columns represent the attributes of an object. Each column has a column name and contains values that are bound by the same type and size. For example, a column in the table S_DEPT specifies the names of the departments in the organization.</p>
<p><i>A Field</i> is an intersection of a row and a column. A field contains one data value. If there is no data in the field, the field is said to contain a NULL value.</p>
<p><a href="http://mycodelines.files.wordpress.com/2009/02/clip-image002.jpg"><img title="clip_image002" style="display:block;float:none;margin-left:auto;margin-right:auto;border-width:0;" height="303" alt="clip_image002" src="http://mycodelines.files.wordpress.com/2009/02/clip-image002-thumb.jpg?w=368&#038;h=303" width="368" border="0" /></a></p>
<p><i>A Primary key</i> is a column or a combination of columns that is used to uniquely identify each row in a table. For example, the column containing department numbers in the S_DEPT table is created as a primary key and therefore every department number is different. A primary key must contain a value. It cannot contain a NULL value.</p>
<p><i>A Foreign key</i> is a column or set of columns that refers to a primary key in the same table or another table. You use foreign keys to establish principle connections between, or within, tables. A foreign key must either match a primary key or else be NULL. Rows are connected logically when required. The logical connections are based upon conditions that define a relationship between corresponding values, typically between a primary key and a matching foreign key. This relational method of linking provides great flexibility as it is independent of physical links between records.</p>
</p>
<p><a href="http://mycodelines.files.wordpress.com/2009/02/clip-image00221.jpg"><img title="clip_image002[21]" style="display:block;float:none;margin-left:auto;margin-right:auto;border-width:0;" height="286" alt="clip_image002[21]" src="http://mycodelines.files.wordpress.com/2009/02/clip-image00221-thumb.jpg?w=376&#038;h=286" width="376" border="0" /></a></p>
</p>
<p>WordPress Tags: <a href="http://wordpress.com/tag/DBMS" rel="Tag">DBMS</a>,<a href="http://wordpress.com/tag/Relational Model" rel="Tag">Relational Model</a>,<a href="http://wordpress.com/tag/Model" rel="Tag">Model</a>,<a href="http://wordpress.com/tag/database" rel="Tag">database</a>,<a href="http://wordpress.com/tag/Column" rel="Tag">Column</a>,<a href="http://wordpress.com/tag/Primary Key" rel="Tag">Primary Key</a>,<a href="http://wordpress.com/tag/Table" rel="Tag">Table</a>,<a href="http://wordpress.com/tag/Field" rel="Tag">Field</a>,<a href="http://wordpress.com/tag/Foreign Key" rel="Tag">Foreign Key</a>,<a href="http://wordpress.com/tag/RDBMS" rel="Tag">RDBMS</a>,<a href="http://wordpress.com/tag/relationship" rel="Tag">relationship</a>,<a href="http://wordpress.com/tag/columns" rel="Tag">columns</a></p>
<p>
<div class="wlWriterEditableSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:0427148b-71e6-4a1f-a013-f718b995d486" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a href="http://technorati.com/tags/DBMS" rel="tag">DBMS</a>,<a href="http://technorati.com/tags/Relational+Model" rel="tag">Relational Model</a>,<a href="http://technorati.com/tags/Model" rel="tag">Model</a>,<a href="http://technorati.com/tags/database" rel="tag">database</a>,<a href="http://technorati.com/tags/Column" rel="tag">Column</a>,<a href="http://technorati.com/tags/Primary+Key" rel="tag">Primary Key</a>,<a href="http://technorati.com/tags/Table" rel="tag">Table</a>,<a href="http://technorati.com/tags/Field" rel="tag">Field</a>,<a href="http://technorati.com/tags/Foreign+Key" rel="tag">Foreign Key</a>,<a href="http://technorati.com/tags/RDBMS" rel="tag">RDBMS</a>,<a href="http://technorati.com/tags/relationship" rel="tag">relationship</a>,<a href="http://technorati.com/tags/columns" rel="tag">columns</a></div></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Excluindo Constraints Foreign Key no MySQL (drop constraint)]]></title>
<link>http://manoelcampos.wordpress.com/2009/02/04/excluindo-constraints-foreign-key-no-mysql-drop-constraint/</link>
<pubDate>Wed, 04 Feb 2009 12:41:04 +0000</pubDate>
<dc:creator>Manoel Campos da Silva Fh</dc:creator>
<guid>http://manoelcampos.wordpress.com/2009/02/04/excluindo-constraints-foreign-key-no-mysql-drop-constraint/</guid>
<description><![CDATA[O MySQL as vezes nos surpreende, devido ao fato de alguns comandos SQL ANSI não funcionarem nele, co]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>O MySQL as vezes nos surpreende, devido ao fato de alguns comandos SQL ANSI não funcionarem nele, como é o caso do drop constraint para exclusão de chaves estrangeiras, as foreign keys.</p>
<p>O comando padrão, que funciona em vários bancos (Firebird, SQL Server e outros) é <em><strong>alter  table NomeDaTabela drop constraint NomeDaConstraint;</strong></em></p>
<p>Porém, não funciona no MySQL. O comando que deve ser executado é <strong><em>alter  table NomeDaTabela drop foreign key NomeDaConstraint;</em></strong></p>
<p>Se você criou uma constaint sem um nome, o sistema InnoDB do MySQL gera um automaticamente. Para saber qual o nome gerado execute <em><strong>show create table NomeDaTabela</strong></em>; Este comando mostra a estrutura da tabela, com as constraints existentes e seus respectivos nomes. Daí, basta executar <strong><em>alter  table NomeDaTabela drop foreign key NomeDaConstraint;</em></strong> para apagar a foreign key desejada.</p>
<p>Referência: <a href="http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html">MySQL 5.1 Reference Manual</a><strong><em><br />
</em></strong></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[PostgreSQL foreign keys and indexes]]></title>
<link>http://scottmoonen.com/2008/12/19/postgresql-foreign-keys-and-indexes/</link>
<pubDate>Fri, 19 Dec 2008 16:15:30 +0000</pubDate>
<dc:creator>Scott Moonen</dc:creator>
<guid>http://scottmoonen.com/2008/12/19/postgresql-foreign-keys-and-indexes/</guid>
<description><![CDATA[If you&#8217;re a frequent user of MySQL, you may be familiar with the fact that all MySQL table con]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://www.postgresql.org/"><img style="border:0 none;float:right;margin:.5em;" src="http://smoonen.wordpress.com/files/2008/12/postgres.gif" alt="[PostgreSQL]" width="95" height="51" /></a>If you&#8217;re a frequent user of MySQL, you may be familiar with the fact that all MySQL table constraints automatically create indexes for you.  This is true of the <a href="http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html">InnoDB foreign key constraints</a>, for which &#8220;an index is created on the referencing table automatically if it does not exist.&#8221;</p>
<p>If you&#8217;re switching or considering a switch to PostgreSQL, you should be aware that not all PostgreSQL table constraints will automatically create indexes for for you.  In PostgreSQL, a UNIQUE or PRIMARY KEY constraint on one or more fields <em>will</em> implicitly create an index for you.  However, in PostgreSQL a FOREIGN KEY constraint will <em>not</em> automatically create an index for you.</p>
<p>For each of your foreign key constraints, you should evaluate whether you want to create an index.  You may want to do this for optimizing your own queries, but be aware that it can also help to speed up DELETE queries on the referenced table and UPDATE queries on the referenced field.  This is because any foreign key reference must be located to enforce whatever ON DELETE and ON UPDATE behavior is in effect for the constraint.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Foreign keys]]></title>
<link>http://dialoguewithmonetdb.wordpress.com/2008/09/20/foreign-keys/</link>
<pubDate>Sat, 20 Sep 2008 17:24:51 +0000</pubDate>
<dc:creator>amatoori</dc:creator>
<guid>http://dialoguewithmonetdb.wordpress.com/2008/09/20/foreign-keys/</guid>
<description><![CDATA[FOREIGN KEYs So I created also the foreign key successfully and now I&#8217;m wondering why the MATC]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>FOREIGN KEYs</p>
<p>So I created also the foreign key successfully and now I&#8217;m wondering why the MATCH FULL foreign key is created when product_type field is NULL. Should the DBMS prevent such foreign key creation?<br />
Well, the manual says this:</p>
<blockquote><p>&#8220;The null matching on foreign keys is limited to the simple match type (null values satisfy the constraint). The full and partial match types are not supported. The referential action is currently limited to restrict, i.e. an update fails if other columns have references to it.&#8221;</p>
<p><a href="http://monetdb.cwi.nl/projects/monetdb/SQL/Documentation/Table-Definition.html#Table-Definition">http://monetdb.cwi.nl/projects/monetdb/SQL/Documentation/Table-Definition.html#Table-Definition</a></p></blockquote>
<p>Like when I create these tables:</p>
<p><code>CREATE TABLE entity (<br />
id INTEGER,<br />
name CHAR(5),<br />
PRIMARY KEY (id, name)<br />
);</code></p>
<p><code>CREATE TABLE sub_entity (<br />
id INTEGER,<br />
name VARCHAR(10),<br />
entity_id INTEGER,<br />
entity_name CHAR(5),<br />
PRIMARY KEY (id),<br />
FOREIGN KEY (entity_id, entity_name) REFERENCES entity (id, name) MATCH FULL<br />
);</code></p>
<p>And do these insertions:</p>
<p><code>INSERT INTO entity VALUES (1,'ABCDE');<br />
INSERT INTO sub_entity VALUES (3,'sub3',NULL,'ABCDE');<br />
INSERT INTO sub_entity VALUES (1,'sub1',NULL,NULL);</code></p>
<p>The foreign key&#8217;s MATCH FULL does not prevent the insertion of NULL into one or both of the table&#8217;s foreign key columns.</p>
<p>The cascading works as follows:<br />
I add cascading (other than restrict) into the foreign key:</p>
<p><code>ALTER TABLE sub_entity ADD FOREIGN KEY (entity_id,entity_name) REFERENCES entity (id,name)<br />
ON DELETE CASCADE ON UPDATE CASCADE;</code></p>
<p>Then I&#8217;ll update id column of entity table:</p>
<p><code>UPDATE entity<br />
SET id = 2<br />
WHERE id = 1;</code></p>
<p>The cascading is not done into sub_entity table, but no integrity constraint violations is given. That update works because there is in sub_entity table only (1, NULL) or (NULL, &#8216;ABCDE&#8217;) value pairs in entity_id and entity_name columns so the foreign key does not work even partially because SIMPLE match is only implemented.</p>
<p>So when no NULLs and wrong entity_id (or wrong entity_name) then the foreign key constraint works and this gives an error:</p>
<p><code>INSERT INTO sub_entity VALUES (11,'sub2',1,'ABCDE');</code></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Vincoli interrelazionali]]></title>
<link>http://ipertesto.wordpress.com/2008/06/19/vincoli-interrelazionali/</link>
<pubDate>Thu, 19 Jun 2008 16:37:41 +0000</pubDate>
<dc:creator>m3kh</dc:creator>
<guid>http://ipertesto.wordpress.com/2008/06/19/vincoli-interrelazionali/</guid>
<description><![CDATA[I vincoli interrelazionali più diffusi e significativi so i vincoli di integrità referenziale. In SQ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I vincoli interrelazionali più diffusi e significativi so i <em>vincoli di integrità referenziale</em>. In SQL per la loro definizione si usa l&#8217;apposito vincolo di <strong>foreign key</strong>, ovvero <em>chiave esterna</em>. Questo vincolo crea un legame tra i valori di un attributo della tabella su cui è definito (Tabella interna) e i valori di un&#8217;attributo di un&#8217;altra tabbella (Tabella esterna). Il vincolo impone che per ogni riga della tabella il valore dell&#8217;attributo specificate, se diverso dal valore nullo, sia presente nelle righe ella tabella esterna tra i valori del corrispondente attributo. L&#8217;unico requisito che la tabella impone è il vincolo <em>unique</em> in fatti tipicamente l&#8217;attributo della tabella esterna cui si fa riferimento rappresenta in effetti la chiave primaria della tabella. Se c&#8217;è un solo attributo coinvolto si può usare il costrutto sintattico <strong>references</strong>, con il quale si specifica che la tabella esterna e l&#8217;attributo della tabella esterna al quale l&#8217;attributo in questione deve essere legato.<strong><br />
Es:</strong></p>
<blockquote><p>create table Impiegato (<br />
Matricola char ( 6 ) primary key,<br />
Nome varchar ( 20 ) not null,<br />
Cognome varchar ( 20 ) not null,<br />
Dipart varchar ( 15 )<br />
<strong>reference</strong> <em>Dipartimento</em> (<em> NomeDip </em>),<br />
Ufficio numeric ( 13 ),<br />
Stipendio numeric ( 9 ) default 0,<br />
unique ( Cognome, Nome )<br />
)</p></blockquote>
<p>Il vincolo impone che l&#8217;attributo <em>Dipart</em> della tabella Impiegato possa assumere solo uno dei valori che le riche della tabella <em>Dipartimento</em> possiedono per l&#8217;attributo <em>NomeDip</em>.</p>
<p>Quando il legame invece è rappresentato da un&#8217;insieme di attributi, fa uso invece del costrutto <strong>foreign key</strong>, posto al termine della definizione degli attributi.<br />
<strong>Es:</strong> Se si volesse prendere la tabella di prima e imporre che gli attributi Nome e Cognome debbano comparire in una tabella anagrafica, si potrebbe aggiungere il vincolo</p>
<blockquote><p>foreing key ( Nome, Cognome )<br />
reference Anagrafica ( Nome , Cognome )</p></blockquote>
</div>]]></content:encoded>
</item>

</channel>
</rss>
