I want to retrieve each column name and data type then check if the columns is foreign key then query they key table of that relation !!! could be done ?? I googled for 3 days I know that I have to use Mappping model OR Reflection or both ,,,, but i cant do it .
I will simplify what i need assuming :
TABLE1 hase foreign key( COL3) refer to the primary key (COL1) in TABLE0 :
iterate TABLE1 Columns check EACH columns if it is a foreign key ( also get its data type)
Get the relation to determine the associated table(TABLE0)
retrieve the primary key tables (TABLE0)
I got it
I make a function that return the type of each foreign key and the related table class type
Private Function GetForeignKeyTables(ByVal myTableType As Type) As List(Of myForeignKeys)
Dim myDx = New Tester.DataClasses1DataContext
Dim mymodel As New AttributeMappingSource
Dim myAsociations = mymodel.GetModel(GetType(DataClasses1DataContext)).GetTable(myTableType).RowType.Associations
Dim asc = From m In myAsociations Where m.IsForeignKey
Select New myForeignKeys With {.KeyDataType = m.ThisKey.First.DbType, .RelatedTableType = m.OtherType}
Return asc.ToList
End Function
Private Class myForeignKeys
Property KeyDataType As String
Property RelatedTableType As MetaType
End Class
But I still need to retrieve the data from those related table .
I mean how to create an instance of the class from its MetaType variable?
Related
Below I load a dataset, which I believe is table 0. Then I set the name of table 0 in the dataset to PickTable:
PickDataSet.ReadXml(My.Computer.FileSystem.SpecialDirectories.MyDocuments & Pickfile)
PickDataSet.Tables(0).TableName = "PickTable"
I'm having trouble now finding syntax to set the primary key for the PickTable. Column 0 is unique and always has a value. I need to make this the primary key.
I tried something like this:
PickDataSet.Tables("PickTable").PrimaryKey = PickDataSet.Tables("PickTable").Columns(0);
The .PrimaryKey property of DataTable expect an array of DataColumn objects. So you can set the first column as primary key with the following line:
PickDataSet.Tables("PickTable").PrimaryKey = {PickDataSet.Tables("PickTable").Columns(0)}
'or
PickDataSet.Tables("PickTable").PrimaryKey = New DataColumn() {PickDataSet.Tables("PickTable").Columns(0)}
I searched but only could found partial answer to this question
The goal would be here to create a new ID column on an existing table.
This new column would be the primary key for the table and I simply want it to be filled with integer values from 1 to number of rows.
What would be the query for that?
I know I have to first alter table to create the new column :
ALTER TABLE <MYTABLE> ADD (ID INTEGER);
Then I could use the series generator :
INSERT INTO <MYTABLE.ID> SELECT SERIES_GENERATE_INTEGER(1,1,(number of rows));
Once the column is filled I could use this line:
ALTER TABLE <MYTABLE> ADD PRIMARY KEY ("ID");
I am sure there is an easier way to do this
You wrote that you want to add a "new ID column to an existing table" and fill it with unique values.
That's not a "standard" operation in any DBMS, as the usual assumption is that records are created with a primary key and not retro fitted.
Thus, "ease" of operation for this is relative to what else you want to do.
For example, if you want to continue using this ID as a primary key for further operations, then using a once-off generator function like the SERIES_GENERATE_INTEGER or a query won't be very helpful since you have to avoid duplicates of already existing values.
Two, relatively easy, options come to mind:
Using a sequence:
create sequence myid;
update <table> set ID = myid.nextval;
And for succeeding inserts:
insert into <table> (id, ..., ...) VALUES (myid.nextval, ..., ...) ;
Note that this generates a value for every existing record and not a predefined set of size X.
Using a GUID
By using a GUID you generate a unique value every time you call the 'SYSUUID' function in SAP HANA. check docu here
Something like
update <table> set ID = SYSUUID;
should do the trick here.
Subsequent inserts would simply call the function for values of ID.
I'm pretty new to the SQL and I have some troubles using foreign keys in my table — it takes a lot of queries to insert/update a single row of such table.
So, basically I have a structure of 4 tables which I use to store "key = value" relation for IRC channels:
msg
-id integer //primary key
-srv_id //integer
-chan_id //integer
-usr_id //integer
-key //text
-value //text
.
srv
-id //integer primary key
-name //text
.
chan
-id //integer primary key
-name //text
.
usr
-id //integer primary key
-name //text
srv_id, chan_id and usr_id in msg table are foreign keys from next three tables.
I need to note that users are allowed to overwrite other's keys, so when user is adding a "key = value" relation I need either to insert new row in msg table or update existing value and usr_name for given srv_name, chan_name and key.
Question: how do I efficiently add a row (or update it if the given key already exist in msg table) knowing: msg.key = 'some_msg_key', msg.value = 'new_msg_value', srv.name = 'some_srv_name', chan.name = 'some_chan_name' and usr.name = 'some_usr_name' that might not be in the tables yet.
Right now I'm doing something like this:
SELECT id FROM srv WHERE name = 'some_srv_name'
check if I got id, if not I do
INSERT INTO srv WHERE name = 'some_srv_name'
and then I get it's id with
SELECT id FROM srv WHERE name = 'some_srv_name'
then I do the same for chan table and for usr table.
it's 9 queries when the srv, chan and urs names are totally new. isn't it horrible? and that is not the end — my goal is to add new row to the msg table or update it if it exists (based on the key value).
so, when I know that 'some_srv_name', 'some_chan_name' and 'some_usr_name' are in tables and I got their ids, I check if there exists a row with such ids and key value = 'some_msg_key':
SELECT id FROM msg WHERE srv_id = 'id_from_previous_queries' AND chan_id = 'id_from_previous_queries' AND key = 'some_msg_key'
if I get anything, I know that the row exists and I need to update it, so I do:
UPDATE msg SET usr_id = 'id_from_previous_queries', key = 'some_msg_key', value = 'new_msg_value' WHERE id = 'id_from_right_above'
if I get nothing, I know that there is no such row and I need to insert it:
INSERT INTO msg VALUES(null, 'id_from_previous_queries', 'id_from_previous_queries', 'id_from_previous_queries', 'some_msg_key', 'new_msg_value')
So, in total I do 5-11 queries.
I wonder if there is a better way with less number of queries to add/update a row in msg table knowing only names of srv, chan and usr that might not be in tables yet.
Note: I use SQLite
Yes, you can do this more easily. First build the lookup tables and then the final msg table. Say you have non-normalized data in a table, src, and you want to insert it.
First, you have to insert new values into each lookup table, using queries such as:
insert into srv(name)
select distinct name
from src
where name not in (select name from srv)
The id should be assigned automatically by declaring it to be an auto increment/identity/serial column (depending on your database).
Do this for each lookup table. Then do the following to insert into the msg table:
insert into msg(srv_id, chan_id, usr_id, key, value)
select srv.srv_id, chan.chan_id, . . .
from src join
srv
on src.name = srv.src_name join
chan
on chan.name = srv.chan_name . . .
You should not have to change the value of a primary key. You should look-up how to work with stored procedure and triggers.
I have the Tables
PatientEligibilit
and
PatientsEligibilitiesDoctorsSpecialties
and
DoctorsSpecialties
PatientEligibilit
has foreign key PatientsEligibilitiesDoctorsSpecialtyID from
PatientsEligibilitiesDoctorsSpecialties
table
and
PatientsEligibilitiesDoctorsSpecialty
has foreign key DoctorsSpecialtyID from
DoctorsSpecialties
table
THEN USING VB.NET LINQ: i'm tring to add child item ( PatientsEligibilitiesDoctorsSpecialty)
to it's parent (PatientEligibilit)
then I submit Changes
like :
PatientEligibilityObject.PatientsEligibilitiesDoctorsSpecialties.Add(New PatientsEligibilitiesDoctorsSpecialty With {.DoctorSpecialtyID = si.ID, .RegDate = Date.Now}) PatientEligibilityObject.PatientsEligibilitiesDoctorsSpecialties.Add(PEDS)
HMSData.SubmitChanges()
it's worked fine and save record in Database with correct date
BUT
DoctorSpecialtyID
always saved with value 1
I solve it. the problem was in the relation between the tables.
The foreign key between PatientEligibilit and PatientsEligibilitiesDoctorsSpecialties
was not correct..
I have a unique situation working with a legacy application where I have a parent/child relationship that is based on two integer values. Unfortunately, these fields are not id and parentId or something similar. The columns are ItemId and SubItemId. When these two columns equal each other, the item is assumed to be a parent. When they differ, the ItemId references the Items parent and the SubItemId is simply an identifier of which child it is.
Here is an example
ItemId = 1, SubItemId = 1: Parent Item
ItemId = 1, SubItemId = 6: Sub Item, whose parent is the Item where the id fields are (1, 1)
ItemId = 2, SubItemId = 2: Parent Item
ItemId = 2, SubItemId = 9: Sub Item, whose parent is the Item where the id fields are (2, 2)
So with this information, I have a class hierarchy set up like this:
public class Item
public property ItemId as Integer
public property SubItemId as Integer
end class
class ParentItem : Item
end class
class SubItem : Item
public property ParentItem as ParentItem
end class
So I would like to map the ParentItem property of the SubItem class to its corresponding ParentItem using NHibernate and I can't for the life of me figure out how. I was able to get NHibernate to instantiate the correct class based on a formula discriminator, and I was hoping something similar was available for many-to-one relationships.
I'm not able to change the table structure, which certainly limits my options. Also, I'm using FluentNHibernate for my mappings, so feel free to offer suggestions using its syntax.
Thanks!
Update
I created a view that added two new columns that equated to a foreign key pointing to the parent and now I'm getting an NHibernate mapping error:
Foreign key (FK163E572EF90BD69A:ItemsNHibernateView [ParentItemID, ParentrSubitemID])) must have same number of columns as the referenced primary key (ItemsNHibernateView [ItemID, SubitemID])
This is throwing me off because to me, it looks like both keys do have the same number of columns...
Ok, I figured it out based on the comment from Ben Hoffstein. I created the view as I mentioned in the update to my original question. The error was caused by an embarassingly stupid error. When I created the array to list the column names for the foreign key, I put both names in the quotes like this:
new string() {"ParentItemID, ParentSubitemID"}
instead of:
new string() {"ParentItemID", "ParentSubitemID"}
The way that NHibernate was displaying the error threw me off the scent.