Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
m-arab
Starting Member
3 Posts |
Posted - 2011-01-09 : 03:59:40
|
Hi,I have tow tables like below:Table1:T1ID (unique)Table2FKT1ID (Foreign key to Table 1)Property (It is optional)I need to join tables and select randomly one of the properties of each entity in Table1, some entities dont have any property in Table2 and some have more than one. But I dont know how to write it correctly,Help me plz |
|
dearabi
Starting Member
2 Posts |
Posted - 2011-01-09 : 05:29:02
|
Hi I use This Code For Join Two Tables That I Need That QuerySELECT T1.fields[,T2.Fields] FROM T1 left JOIN T2 ON T1.T1ID= T2.T1ID{Also In Some Projects I Use This C# Code for Getting My Data (For Ex:For Getting The Name Of Company_Name As I Change The Name Of ShahrestanName that Are Located On COmboBoxHere IS My Code :this.cBcompName.Items.Clear(); SqlCommand cmd = new SqlCommand("SELECT * FROM Tcompany where shahrestanName =N'" + cbShahrestan.Text + "'", conn); this.conn.Open(); SqlDataReader rsBooks = cmd.ExecuteReader(); while (rsBooks.Read()) { this.cBcompName.Items.Add(rsBooks.GetString(0)); } rsBooks.Close(); this.conn.Close(); cBcompName.Enabled = true;That Conn is My Connection_String And cBcompName is ComboBox that I use it for Store my Data,TCompant Is My Tables That I Want To Get Data(Common Data) And ShahrestanName Is Common Field.}Hope It Can Help You |
 |
|
m-arab
Starting Member
3 Posts |
Posted - 2011-01-09 : 10:06:15
|
Thanks guy,But it does not work correctly, I need to do all with T-SQL |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-01-09 : 13:02:25
|
[code]SELECT t1.*,t2.PropertyFROM Table1 t1OUTER APPLY (SELECT TOP 1 Property FROM Table2 WHERE FKT1ID = t1.T1ID ORDER BY NEWID() )t2[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
m-arab
Starting Member
3 Posts |
Posted - 2011-01-10 : 03:44:24
|
Thanks Visakh, It works truely |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-01-10 : 11:17:11
|
Welcome------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|