Thursday, May 11, 2006

Adding Foreign Keys after a table has been created

Well, you knew exactly what you needed when you created a table. Only now when you created a child table, the child table does not update with the information from your main table. Or worse you deleted something from your primary table and it still lives in the child table. You need a foreign key, my friend. This is how you define one after you've created your table.
ALTER TABLE My_Child_Table ADD CONSTRAINT FK_User_ID
FOREIGN KEY ( User_ID_In_Child_Table )
REFERENCES My_Primary_Table ( User_ID_In_Primary_Table )
ON DELETE CASCADE

ON UPDATE CASCADE
The last two lines are important. In this example, if the user id in the primary table is modified or deleted, the change will cascade to the child table. This ensures consistency between the two tables.

As always, this works on SQL Server. Check your documentation for mySql, Oracle, etc.

Monday, May 08, 2006

Converting Double to String with J#

So, you made an awesome function that does cool things. Only the return type is a double and you have to display it as a string. No problem, you'll just have to convert it using this little snippet:
String my_String_for_Display = new String();
my_String_for_Display = Double.toString(my_Function());
This should would for C# as well, with minor modifications, but check the MSDN pages. This will also work for a double value instead of a function call, function with parameters, etc.

Thursday, January 12, 2006

Adding Checks after a table has been created

Did you create a table, only to find that you need to add a check constraint?
It happened to me, and I hopped on google to find the code. In this example, we'll use my fictional User table. We want to know if our user is alive or dead. 1 = alive, 0 = dead. Here is the code for SQL server:
alter table dbo.Tbl_User_Table add constraint
CK_User_Alive check (User_Alive in (0,1))
I don't know if it will work with MySql, Oracle, etc, so check your documentation. Happy Coding!