Luciano Evaristo Guerche

A brazilian geek interested in .NET technologies

About Me

That's why I love Textpad and regular expressions

Suppose you have a lot of ALTER TABLE statements, like the one below (I actually had 30+) and you find out you must delete inconsistent data on child table before procceeding on constraint creation.

ALTER TABLE dbo.ChildTable
       ADD CONSTRAINT FK_ChildTable_ParentTable
              FOREIGN KEY (ChildField)
                             REFERENCES dbo.ParentTable (ParentField)
GO


What would you do? Manually add a DELETE statement before each ALTER table statement? No, in my case, I used Textpad and regular expressions. You can check just below

Find: ALTER TABLE[ ]+\(.+\)\n[ ]+ADD CONSTRAINT[ ]+\(.+\)\n[ ]+FOREIGN KEY[ ]+(\(.+\))\n[ ]+REFERENCES[ ]+\(.+\)[ ]+(\(.+\))\nGO\n
Replace with: DELETE \1\nFROM \1\n LEFT JOIN\n \4 ON \1.\3 = \4.\5\nWHERE \1.\3 IS NOT NULL AND \4.\5 IS NULL\nGO\n\n&\n

and then I got a pair of SQL statements for each ALTER TABLE, like the one below

DELETE dbo.ChildTable
FROM dbo.ChildTable
  LEFT JOIN
     dbo.ParentTable ON dbo.ChildTable.ChildField = dbo.ParentTable.ParentField
WHERE dbo.ChildTable.ChildField IS NOT NULL AND dbo.ParentTable.ParentField IS NULL
GO

ALTER TABLE dbo.ChildTable
       ADD CONSTRAINT FK_ChildTable_ParentTable
              FOREIGN KEY (ChildField)
                             REFERENCES dbo.ParentTable (ParentField)
GO

Comments

patag said:

Textpad and RegEx rule the world, two of the most powerful tools known to programmers!
# July 8, 2004 7:34 PM

tuhinbal said:

Hi,
Can u tell me how to configure text pad to run sql statements without sqlplus?



Tuhin
Tata Consultancy Services
India
mail id: tuhinbal@rediffmail.com
# July 18, 2004 5:24 AM

Luciano Evaristo Guerche said:

Tuhin,

In Textpad, you can add external programs to be run from Textpad through the tools menu. As I work with SQL server, what I would do is to configure Textpad to run osql.exe passing the file I am working on in Textpad. So, with file containing the SQL statement open on Textpad, I would select Tools > osql menu, osql.exe would be started using current file and Textpad would capture the output to Textpad output area.
# July 18, 2004 10:04 AM

Luciano Evaristo Guerche said:

Tuhin,

In your case, you must check whether Oracle has a command line tool to run SQL statements, like osql.exe in SQL server.
# July 18, 2004 10:05 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)